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

2024-02-13

有没有办法在 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();

  • As of seaborn 0.11.2 https://seaborn.pydata.org/whatsnew.html#v0-11-2-august-2021
    • seaborn.distplot https://seaborn.pydata.org/generated/seaborn.distplot.html替换为图形级别seaborn.displot https://seaborn.pydata.org/generated/seaborn.displot.html#seaborn.displot和轴水平seaborn.histplot https://seaborn.pydata.org/generated/seaborn.histplot.html#seaborn.histplot,其中有一个stat范围。使用stat='percent'.
  • For both types of plots, experiment with common_binsand common_norm.
    • 例如,common_norm=True将显示占总人口的百分比,而False将显示相对于该组的百分比。
  • 此中所示的实现answer https://stackoverflow.com/a/68851142/7758804展示如何添加注释。
import seaborn as sns
import matplotlib.pyplot as ply

# data
data = sns.load_dataset('titanic')

图形级别

p = sns.displot(data=data, x='age', stat='percent', hue='sex', height=3)
plt.show()
p = sns.displot(data=data, x='age', stat='percent', col='sex', height=3)
plt.show()
  • 类型注释 (:=)用于labels需要python >= 3.8。这可以通过以下方式实现:for-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()

轴水平

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

按组别百分比

  • Use the common_norm=范围
  • See seaborn histplot 和 displot 输出不匹配 https://stackoverflow.com/q/68865538/7758804
p = sns.displot(data=data, x='age', stat='percent', hue='sex', height=4, common_norm=False)
p = sns.displot(data=data, x='age', stat='percent', col='sex', height=4, common_norm=False)
fig = plt.figure(figsize=(5, 4))
p = sns.histplot(data=data, x='age', stat='percent', hue='sex', common_norm=False)
plt.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用seaborn distplot / histplot / displot绘制百分比 的相关文章

随机推荐