【问题标题】:How to plot percentage with seaborn distplot / histplot / displot如何使用 seaborn distplot / histplot / displot 绘制百分比
【发布时间】:2020-12-02 00:08:17
【问题描述】:

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

【问题讨论】:

    标签: python pandas seaborn


    【解决方案1】:
    • 截至seaborn 0.11.2
    • 对于这两种类型的绘图,请使用common_binscommon_norm 进行试验。
      • 例如,common_norm=True 将显示占整个人口的百分比,而False 将显示相对于该组的百分比。
    • answer 中显示的实现展示了如何添加注释。
    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()
    

    按组划分的百分比

    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()
    

    【讨论】:

      【解决方案2】:

      你可以使用norm_hist = True

      来自documentation

      norm_hist:布尔值,可选

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

      【讨论】:

      • 此方法给出了不想要的结果,例如在sns.distplot([1,2,2], norm_hist=True) 中,y 轴的值总和不等于 1。
      【解决方案3】:

      您可以选择条形图,并设置一个以百分比定义归一化的估计器:

      import numpy as np
      import pandas as pd
      import seaborn as sns
      import matplotlib.pyplot as plt
      
      df = pd.DataFrame(dict(x=np.random.poisson(10, 1_000)))
      ax = sns.barplot(x="x",
                       y="x",
                       data=df,
                       palette=["teal", "crimson"],
                       estimator=lambda x: len(x) / len(df) * 100
                       )
      ax.set(xlabel="tenure")
      ax.set(ylabel="Percent")
      
      plt.show()
      

      给予:

      【讨论】:

        猜你喜欢
        • 2021-02-13
        • 2018-02-13
        • 2021-10-22
        • 2023-03-23
        • 2016-05-25
        • 2019-05-15
        • 2021-05-10
        • 2021-11-02
        相关资源
        最近更新 更多