来自 Pandas Dataframe 的 Seaborn Violin Plot,每列都有自己独立的小提琴图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46134113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:25:34  来源:igfitidea点击:

Seaborn Violin Plot from Pandas Dataframe, each column its own separate violin plot

pandasseaborn

提问by aw94

I have Pandas Dataframe with structure:

我有 Pandas Dataframe 的结构:

   A  B
0  1  1
1  2  1
2  3  4
3  3  7
4  6  8

How do I generate a Seaborn Violin plot with each column as its own separate violin plot for side-by-side comparison?

如何生成一个 Seaborn Violin 图,每列作为它自己单独的小提琴图进行并排比较?

回答by jezrael

You can first reshape by meltfor groups from columns and then seaborn.violinplot:

您可以首先通过meltfor 来自列的组重新整形,然后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)

graph

图形

回答by Nathan

seaborn(at least, version 0.8.1; not sure if this is new) supports what you want without messing around with your dataframe at all:

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)

violin plot

小提琴情节

(Note that you do need to set data=df; if you just pass in dfas the first argument (equivalent to setting x=dfin the function call), it seems like it concatenates the columns together and then makes a violin plot of all of the data)

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