如何使用seaborn distplot / histplot / displot绘制百分比

Luc*_*deu 7 python pandas seaborn displot histplot

有没有办法在 distplot 上绘制百分比而不是计数?

ax = sns.FacetGrid(telcom, hue='Churn', palette=["teal", "crimson"], size=5, aspect=1)
ax = ax.map(sns.distplot, "tenure",  hist=True, kde=False)
ax.fig.suptitle('Tenure distribution in customer churn', y=1, fontsize=16, fontweight='bold');
plt.legend();
Run Code Online (Sandbox Code Playgroud)

代码生成的图像

Tre*_*ney 16

  • 作为seaborn 0.11.2
  • 对于这两种类型的图,请使用common_bins和进行实验common_norm
    • 例如,common_norm=True将显示占整个人口的百分比,而False将显示相对于该组的百分比。
  • 此答案中显示的实现展示了如何添加注释。
import seaborn as sns
import matplotlib.pyplot as ply

# data
data = sns.load_dataset('titanic')
Run Code Online (Sandbox Code Playgroud)

图形级别

p = sns.displot(data=data, x='age', stat='percent', hue='sex', height=3)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

p = sns.displot(data=data, x='age', stat='percent', col='sex', height=3)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 在requires:=中使用类型注释( ) 。这可以通过 a 来实现,而不需要使用.labelspython >= 3.8for-loop:=
fg = sns.displot(data=data, x='age', stat='percent', col='sex', height=3.5, aspect=1.25)

for ax in fg.axes.ravel():
    
    # add annotations
    for c in ax.containers:

        # custom label calculates percent and add an empty string so 0 value bars don't have a number
        labels = [f'{w:0.1f}%' if (w := v.get_height()) > 0 else '' for v in c]

        ax.bar_label(c, labels=labels, label_type='edge', fontsize=8, rotation=90, padding=2)
    
    ax.margins(y=0.2)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

轴水平

fig = plt.figure(figsize=(4, 3))
p = sns.histplot(data=data, x='age', stat='percent', hue='sex')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

按组别百分比

p = sns.displot(data=data, x='age', stat='percent', hue='sex', height=4, common_norm=False)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

p = sns.displot(data=data, x='age', stat='percent', col='sex', height=4, common_norm=False)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

fig = plt.figure(figsize=(5, 4))
p = sns.histplot(data=data, x='age', stat='percent', hue='sex', common_norm=False)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 这真太了不起了!我一直在寻找如何做到这一点,非常感谢! (2认同)

小智 0

你可以使用norm_hist = True.

文档中:

norm_hist:布尔值,可选

如果为 True,则直方图高度显示密度而不是计数。如果绘制 KDE 或拟合密度,则暗示这一点。