Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subplot for seaborn boxplot

People also ask

Can we use subplots in Seaborn?

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.

What is subplot in Seaborn?

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.

How do you do a box plot in Seaborn?

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.

How do you plot multiple subplots in Seaborn?

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:

enter image description here


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)

enter image description here


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()

enter image description here