'Subplot for seaborn boxplot
I have a dataframe like this
import seaborn as sns
import pandas as pd
%pylab inline
df = pd.DataFrame({'a' :['one','one','two','two','one','two','one','one','one','two'],
'b': [1,2,1,2,1,2,1,2,1,1],
'c': [1,2,3,4,6,1,2,3,4,6]})
A single boxplot is OK:
sns.boxplot(y="b", x="a", data=df, orient='v')
But I want to build a subplot for all variables. I tried:
names = ['b', 'c']
plt.subplots(1,2)
sub = []
for name in names:
ax = sns.boxplot( y=name, x= "a", data=df, orient='v' )
sub.append(ax)
but it outputs:
Solution 1:[1]
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:
Solution 2:[2]
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()
Solution 3:[3]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Lucas |
Solution 2 | |
Solution 3 | iacob |