Christina Zhou
Christina Zhou

Reputation: 1863

make boxplot with columns from 2 dataframes [python seaborn]

I want to make a boxplot like this:

enter image description here

My data looks like this. It's separated into a control and an intervention dataframe.

control_df
   # of Days
0         10
1         12
2         30
intervention_df
   # of Days
0          2
1          1
2          2

Unfortunately, I'm not able to easily put it into sns.boxplot. Any advice on how to format it to graph appreciated.

MVE below:

import pandas as pd

# This is how my actual data is coming in
data_control = {'# of Days':[10,12,30]}
data_intervention = {'# of Days':[2,1,2]}

control_df = pd.DataFrame(data_control)
intervention_df = pd.DataFrame(data_intervention)

# This is me manually making it better for a boxplot
boxplot_data = {'Type':['control','control','control','intervention','intervention','intervention'],
                '# of Days':[10,12,30,2,1,2]}

import seaborn as sns

sns.boxplot(x='Type',y='# of Days',data=boxplot_data)

Upvotes: 0

Views: 77

Answers (1)

Scott Boston
Scott Boston

Reputation: 153550

IIUC, you can use pd.concat with keys parameter and droplevel:

sns.boxplot(data=pd.concat([control_df, intervention_df], 
                           axis=1, 
                           keys=['Control', 'Intervention']).droplevel(1, axis=1))

Output:

enter image description here

Upvotes: 1

Related Questions