pr94
pr94

Reputation: 1413

side-by-side boxplot with multiple Pandas DataFrames

Despite some good previous examples on this site, I have not been able to generate side-by-side boxes for multiple pandas DataFrames in one plot.

I tried this:

import pandas as pd
import matplotlib
import matplotlib.pyplot as plt

df = pd.DataFrame({'A1':[9,16.2,8.1],'A2':[3.3,21.5,4.1],
                   'B1':[8,9.8,1.6],'B2':[10.8,2.2,3.6],
                   'C1':[1.3,2.8,1.6],'C2':[3.1,4.1,3.6],})

df1 = df.loc[:, 'A1':'A2']
df2 = df.loc[:, 'B1':'B2']
df3 = df.loc[:, 'C1':'C2']

fig = matplotlib.pyplot.boxplot(df1)
fig = matplotlib.pyplot.boxplot(df2)
fig = matplotlib.pyplot.boxplot(df3)
plt.show()

enter image description here

But I would like something like this:

enter image description here

In addition, it would be nice if I could display the individual datapoints as dots in the boxes. So if anyone has a suggestion for that too, would be great!

Thank you!

Upvotes: 1

Views: 2199

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40747

If I understand you correctly, you want 6 boxplots with 3 groups of 2 (each group is A/B/C and inside each group you have 1/2)?

You can achieve the desired result fairly easily using seabord, but you must fist refactor your dataframe in "long form". I first use pd.wide_to_long() to split the data in the 3 groups A/B/C with a new column identifying the subgroups 1/2, then I further melt the resulting dataframe to obtain a long form dataframe:

df = pd.DataFrame({'A1':[9,16.2,8.1],'A2':[3.3,21.5,4.1],
                   'B1':[8,9.8,1.6],'B2':[10.8,2.2,3.6],
                   'C1':[1.3,2.8,1.6],'C2':[3.1,4.1,3.6],})

df["id"] = df.index
df = pd.wide_to_long(df, stubnames=['A','B','C'], i='id', j='group').reset_index().drop('id', axis=1)
df = df.melt(id_vars='group')

The resulting dataframe is now this:

    group   variable    value
0   1   A   9.0
1   1   A   16.2
2   1   A   8.1
3   2   A   3.3
4   2   A   21.5
5   2   A   4.1
6   1   B   8.0
7   1   B   9.8
8   1   B   1.6
9   2   B   10.8
10  2   B   2.2
11  2   B   3.6
12  1   C   1.3
13  1   C   2.8
14  1   C   1.6
15  2   C   3.1
16  2   C   4.1
17  2   C   3.6

It is then trivial to use seaborn's boxplot to generate the plot:

sns.boxplot(data=df, x='variable', y='value', hue='group')

enter image description here

If you desire, you can overlay a swarmplot on top of the boxplot to see the individual datapoints

sns.boxplot(data=df, x='variable', y='value', hue='group')
sns.swarmplot(data=df, x='variable', y='value', hue='group', dodge=True, palette=['grey','grey'], s=10)

enter image description here

Upvotes: 2

Related Questions