Pandas Dataframe的Seaborn小提琴图,每列都有自己的单独小提琴图

aw9*_*w94 4 pandas seaborn

我有Pandas Dataframe结构:

   A  B
0  1  1
1  2  1
2  3  4
3  3  7
4  6  8
Run Code Online (Sandbox Code Playgroud)

我如何生成Seaborn小提琴图并将每列作为自己的单独小提琴图进行并排比较?

jez*_*ael 8

您可以首先melt为列中的组重塑,然后seaborn.violinplot

#old version of pandas
#df = pd.melt(df, var_name='groups', value_name='vals')
df = df.melt(var_name='groups', value_name='vals')
print (df)
  groups  vals
0      A     1
1      A     2
2      A     3
3      A     3
4      A     6
5      B     1
6      B     1
7      B     4
8      B     7
9      B     8

ax = sns.violinplot(x="groups", y="vals", data=df)
Run Code Online (Sandbox Code Playgroud)

图形


Nat*_*han 6

seaborn (至少是0.8.1版;不确定是否是新版本)支持您想要的内容,而不会弄乱您的数据框:

import pandas as pd
import seaborn as sns
df = pd.DataFrame({'A': [1, 2, 3, 3, 6], 'B': [1, 1, 4, 7, 8]})
sns.violinplot(data=df)
Run Code Online (Sandbox Code Playgroud)

小提琴情节

(请注意,您确实需要进行设置data=df;如果只是将df第一个参数作为参数传入(相当于x=df在函数调用中进行设置),则似乎将这些列连接在一起,然后绘制所有数据的小提琴图)