How to join pandas dataframe so that seaborn boxplot or violinplot can use a column as hue?

Viewed 1512

I have a dataframe with multiple columns, and I can easily use seaborn to plot it in a boxplot (or violinplot, etc), like this:

data1 = {'p0':[1.,2.,5,0.], 'p1':[2., 1.,1,3], 'p2':[3., 3.,2., 4.]}
df1 = pd.DataFrame.from_dict(data1)
sns.boxplot(data=df1)

enter image description here

What I now need is to merge this dataframe with another one, so that I can plot them in a single boxplot, just as is done here: http://seaborn.pydata.org/examples/grouped_boxplot.html

I have tried adding a column and concatenating. The result seems ok

data1 = {'p0':[1.,2.,5,0.], 'p1':[2., 1.,1,3], 'p2':[3., 3.,2., 4.]}
data2 = {'p0':[3.,1.,5,1.], 'p1':[3., 2.,3,3], 'p2':[1., 2.,2., 5.]}
df1 = pd.DataFrame.from_dict(data1)
df1['method'] = 'A'
df2 = pd.DataFrame.from_dict(data2)
df2['method'] = 'B'
df_all = pd.concat([df1,df2])
sns.boxplot(data=df_all)

This works, but it plots together data from methods A and B. However this fails:

sns.boxplot(data=df_all, hue='method')

because I then need to specify x and y. If I specify x as x=['p0', 'p1', 'p2'], them the 3 columns are averaged. So I guess I can merge the dataframes in a different way so that its representation is simple with seaborn.

3 Answers
Related