用于按分类列拆分单列的 Seaborn 小提琴图

seaborn violin plot for single column splitting by a categorical column

我有一个如下所示的数据框:

    num_column    is_train
    30.75               1
    12.05               1 
    ..                 ..
    43.79               0         
    15.35               0              

我想使用小提琴图查看 num_column 的分布,小提琴的每一侧(或拆分)在 is_train 列中显示我的两个类别中每个类别的数据。

来自 examples in documentation,这是我能想到的:

import seaborn as sns
sns.violinplot(x=merged_data.loc[:,'num_column'], hue=merged_data.loc[:,'is_train'], split=True)

从这个结果来看,我可以看出参数 huesplit 根本没有效果。这意味着小提琴的两侧没有分开,我看不到任何图例,所以我推测 hue 参数没有效果。

我正在尝试比较我的训练数据和测试数据中列的分布。

您可以使用 x= 参数来创建多个小提琴。当需要通过第三列进行区分时,使用 huesplit 参数。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

merged_data = pd.DataFrame({'num_column': 20 + np.random.randn(1000).cumsum(),
                            'is_train': np.repeat([0, 1], 500)})
sns.violinplot(data=merged_data, x='is_train', y='num_column')
plt.show()

split= 参数将与 hue 嵌套一起使用,只有当您已经有 x= 参数时才能使用它。因此,您需要为 x(两个数据集的值应该相同)和 hue(编码取决于数据集)提供列:

merged_data['dummy'] = 0
sns.violinplot(data=merged_data, y='num_column', split=True, hue='is_train', x='dummy')