You can use the following basic syntax to create subplots in the seaborn data visualization library in Python: #define dimensions of subplots (rows, columns) fig, axes = plt. subplots(2, 2) #create chart in each subplot sns.
In this article, we will explore how to create a subplot or multi-dimensional plot in seaborn, It is a useful approach to draw subplot instances of the same plot on different subsets of your dataset. It allows a viewer to quickly extract a large amount of data about complex information.
Plotting a Box Plot in Seaborn If we want to visualize just the distribution of a categorical variable, we can provide our chosen variable as the x argument. If we do this, Seaborn will calculate the values on the Y-axis automatically, as we can see on the previous image.
In Seaborn, we will plot multiple graphs in a single window in two ways. First with the help of Facetgrid() function and other by implicit with the help of matplotlib. data: Tidy dataframe where each column is a variable and each row is an observation.
We create the figure with the subplots:
f, axes = plt.subplots(1, 2)
Where axes is an array with each subplot.
Then we tell each plot in which subplot we want them with the argument ax
.
sns.boxplot( y="b", x= "a", data=df, orient='v' , ax=axes[0])
sns.boxplot( y="c", x= "a", data=df, orient='v' , ax=axes[1])
And the result is:
names = ['b', 'c']
fig, axes = plt.subplots(1,2)
for i,t in enumerate(names):
sns.boxplot(y=t, x="a", data=df, orient='v', ax=axes[i % 2])
Example:
names = ['b', 'c']
fig, axes = plt.subplots(1,2)
sns.set_style("darkgrid")
flatui = ["#95a5a6", "#34495e"]
for i,t in enumerate(names):
sns.boxplot(y=t, x= "a", data=df, orient='v', ax=axes[i % 2], palette=flatui)
If you wish to iterate through multiple different subplots, use plt.subplots
:
import matplotlib.pyplot as plt
# Creating subplot axes
fig, axes = plt.subplots(nrows,ncols)
# Iterating through axes and names
for name, ax in zip(names, axes.flatten()):
sns.boxplot(y=name, x= "a", data=df, orient='v', ax=ax)
Working example:
import numpy as np
# example data
df = pd.DataFrame({'a' :['one','one','two','two','one','two','one','one','one','two'],
'b': np.random.randint(1,8,10),
'c': np.random.randint(1,8,10),
'd': np.random.randint(1,8,10),
'e': np.random.randint(1,8,10)})
names = df.columns.drop('a')
ncols = len(names)
fig, axes = plt.subplots(1,ncols)
for name, ax in zip(names, axes.flatten()):
sns.boxplot(y=name, x= "a", data=df, orient='v', ax=ax)
plt.tight_layout()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With