首页 > 解决方案 > 两个数据帧的所有列的小提琴图,小提琴的每一侧显示同一列但来自另一个数据帧

问题描述

train_df我有两个名为和的熊猫数据框test_df。它们都有同名的列,并且test_df不只有一列train_df。我现在想绘制小提琴图,显示图的每一行中我的数据帧的每一列的分布(如箱线图);小提琴的每一侧代表同一列但来自不同的数据帧,以便比较两个数据帧中每一列的分布。我该怎么做(最好在 matplotlib 或 seaborn 中)?

编辑 1:
类似于下面的这个图,但我希望每把小提琴显示每列的分布,小提琴的每一侧显示每个数据帧中具有相同列的列的分布。除了此图像仅显示两列并使用第三列作为颜色。 在此处输入图像描述

标签: pythonpandasmatplotlibseabornviolin-plot

解决方案


You will have to combine your two dataframe in one, with a column setting the origin of each line:

# create fake data
tips = sns.load_dataset('tips')
train_df = tips.loc[tips['smoker']=='Yes']
test_df = tips.loc[tips['smoker']=='No']

# concatenate both dataframe
df = pd.concat([train_df.assign(orig='train'), test_df.assign(orig='test')], axis=0)

# plot
ax = sns.violinplot(x="day", y="total_bill", hue="orig",
                    data=df, split=True)

推荐阅读