Seaborn,每列一个数据的小提琴图

Seaborn, violin plot with one data per column

我想结合这个小提琴情节http://seaborn.pydata.org/generated/seaborn.violinplot.html (fourth example with split=True) with this one http://seaborn.pydata.org/examples/elaborate_violinplot.html

实际上,我有一个带有列 Success(是或否)和几个数据列的数据框。例如:

df = pd.DataFrame(
    {"Success": 50 * ["Yes"] + 50 * ["No"], 
     "A": np.random.randint(1, 7, 100), 
     "B": np.random.randint(1, 7, 100)}
)

    A  B Success
0   6  4     Yes
1   6  2     Yes
2   1  1     Yes
3   1  2     Yes
.. .. ..     ...
95  4  4      No
96  2  1      No
97  2  6      No
98  2  3      No
99  2  1      No

我想为每个数据列绘制一个小提琴图。它适用于:

import seaborn as sns
sns.violinplot(data=df[["A", "B"]], inner="quartile", bw=.15)

但是现在,我想根据 Success 列拆分小提琴。但是,使用 hue="Success" 我得到了 Cannot use 'hue' without 'x' or 'y' 的错误。因此,我该如何通过根据 "Success" 列拆分来绘制小提琴图?

我能够像这样在 DataFrame 上改编 example 小提琴图:

df = pd.DataFrame({"Success": 50 * ["Yes"] + 50 * ["No"], 
                   "A": np.random.randint(1, 7, 100), 
                   "B": np.random.randint(1, 7, 100)})
sns.violinplot(df.A, df.B, df.Success, inner="quartile", split=True)
sns.plt.show()

显然,它仍然需要一些工作:例如,A 音阶的大小应该适合一把半小提琴。

如果正确理解您的问题,您需要重塑数据框以使其具有长格式:

df = pd.melt(df, value_vars=['A', 'B'], id_vars='Success')
sns.violinplot(x='variable', y='value', hue='Success', data=df)
plt.show()