0

I am trying to use sns.violinplot() to draw vertical violins, grouped by two variables, like the third figure in the documentation.

The issue I am having is that each row of my dataframe represents a different research participant and each column is a different variable (e.g. results from different brain regions or if the participant is a patient or control) and i can't work out how to get the dataframe into the format so it will show the violin plot for patients against controls next to each other.

Example dataframe

     nm_rt_vta_sn_m  nm_lt_vta_sn_m  nm_lt_sn_post_m  nm_rt_sn_post_m  patient
0              0.17            0.20             0.22             0.19        1
1              0.19            0.20             0.23             0.22        1
2              0.22            0.21             0.23             0.24        1
3              0.19            0.19             0.21             0.21        1
4              0.23            0.24             0.25             0.25        1
140            0.22            0.23             0.27             0.24        0
141            0.21            0.21             0.22             0.23        0
142            0.19            0.22             0.24             0.21        0
143            0.21            0.23             0.25             0.22        0
144            0.20            0.21             0.24             0.22        0

I have tried using unstack() stack() and other methods but can't seem to get it work.

Timeless
  • 22,580
  • 4
  • 12
  • 30
Luke Vano
  • 3
  • 2

1 Answers1

0

I think you're looking for melt :

plt.figure(figsize=(8, 4))

sns.violinplot(data=df.melt(id_vars="patient"), x="variable", y="value", hue="patient")

plt.show();

Output :

enter image description here

Timeless
  • 22,580
  • 4
  • 12
  • 30