如何为每个班级和小组生成单独的小提琴图

问题描述 投票:0回答:2

我有一个 pandas 数据框:

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
df['Label'] = np.random.randint(0,2,size=100)

我想在 python 中创建一个图形,其中 x 轴显示类标签(“类 0”和“类 1”),对于每个类以及预定义变量(如“B”)小提琴图(带有箱形图)已创建。

python pandas matplotlib seaborn violin-plot
2个回答
3
投票

导入和数据帧

import pandas as pd
import seaborn as sns
import numpy as np  # for random data

# sample data
np.random.seed(2024)
df = pd.DataFrame(np.random.randint(0, 100, size=(100, 4)), columns=list('ABCD'))
df['Class'] = np.random.randint(0, 2, size=100)

# melt the dataframe to a long form
dfm = df.melt(id_vars='Class', var_name='Group')

# display(dfm.head())
   Class Group  value
0      0     A      8
1      0     A     36
2      0     A     65
3      1     A     66
4      0     A     74

绘图

seaborn.violinplot

ax = sns.violinplot(data=dfm, x='Group', y='value', hue='Class')
sns.move_legend(ax, bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)
  • x='Group', hue='Class'

enter image description here

  • x='Class', hue='Group'

enter image description here

seaborn.catplot

  • 要轻松地为每个组单独绘图,请使用
    seaborn.catplot
    kind='violin'
g = sns.catplot(kind='violin', data=dfm, x='Class', y='value', col='Group', col_wrap=2)

enter image description here


1
投票

使用seaborn,非常简单:

import seaborn as sns
...
sns.violinplot(x=df.Label, y=df.B)
© www.soinside.com 2019 - 2024. All rights reserved.