Alexis
Alexis

Reputation: 2304

Creating a subplot of box plots with free y axis in matplotlib

I have this toy dataset that I want to plot by group:

df_plots = pd.DataFrame({'Group':['A','A','A','A','B','B','B','B','C','C','C','C','D','D','D','D'],\
                         'Value':[1,1.2,1.4,1.3,16,18,16,19,43,47,42,55,0.2,0.4,0.3,0.6]})
df_plots

    Group   Value
0   A   1.0
1   A   1.2
2   A   1.4
3   A   1.3
4   B   16.0
5   B   18.0
6   B   16.0
7   B   19.0
8   C   43.0
9   C   47.0
10  C   42.0
11  C   55.0
12  D   0.2
13  D   0.4
14  D   0.3
15  D   0.6

I want to create boxplots per group, but when I use this code, the plot minimizes one of the groups due to the size of the values:

df_plots.groupby('Group').boxplot(column = 'Value')
plt.show()

enter image description here

So I want the y-axis to be scale free, so I try to create subplots with this code:

fig, axes = plt.subplots(2,2,figsize=(8,6)) 

for i, k in enumerate(df_plots.groupby('Group').groups.keys()):
    group = df_plots.groupby('Group').get_group(k)
    group.boxplot(ax=axes[i], return_type='axes')

But I get an error: 'numpy.ndarray' object has no attribute 'boxplot'

Please, could you help me with my plot?

Upvotes: 0

Views: 830

Answers (1)

Brendan
Brendan

Reputation: 4011

You can use sharey=False to separate the y-axis scales, and flatten the axes to loop over the (2,2) subplots:

fig, axs = plt.subplots(2,2,figsize=(8,6), sharey=False)
axs = axs.flatten()

for i, g in enumerate(df_plots.groupby('Group')):
    g[1].boxplot(ax=axs[i])

Alternatively, seaborn is useful for this kind of task:

import seaborn as sns

sns.catplot(data=df_plots, y='Value', 
            col='Group', col_wrap=2, 
            kind='box', sharey=False)

Upvotes: 2

Related Questions