Plot multiple boxplots from seaborn with hue

Viewed 871

I have a dataframe with three columns

df=pd.DataFrame(data = {'Dose1': [1,2,3,4,5], 'Dose2': [6,6,4,7,4],'SickOrNot':[True,False,True,True,False]})

The last column corresponds to whether or not a patient stayed sick and the first two columns are doses of two drugs administered to the patient. I want to create two pairs of boxplots (in seaborn) of the doses, using whether the patient was sick or not as a hue.

So, essentially, I want the x axis to have two sections (Dose 1, Dose 2), which each section containing two boxplots. So that my final four boxplots are that of Dose 1 of sick patients, dose 1 of non sick patients, dose 2 of sick patients, dose 2 of non sick patients.

What is the syntax that I would use to do this? I have tried setting hue to be 'sick or not' but I am very confused about what to set as my x and y values when calling sns.boxplot.

1 Answers

Reshape the data into long form such that each column is one variable and each row is one observation. In this case Dose1 and Dose2 should be combined into one column, e.g. Section.

melt() the data with SickOrNot as the identifier and Dose1 and Dose2 as the values. Then set SickOrNot as the plot's hue:

sns.boxplot(
    data=df.melt(id_vars=['SickOrNot'], value_vars=['Dose1', 'Dose2'],
                 var_name='Section', value_name='Dosage'),
    x='Section',
    y='Dosage',
    hue='SickOrNot',
)

box plot after melting

Related