簡體   English   中英

如何 plot 百分比與 seaborn distplot / histplot / displot

[英]How to plot percentage with seaborn distplot / histplot / displot

有沒有辦法 plot 百分比而不是 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();

代碼生成的圖像

  • seaborn 0.11.2
  • 對於這兩種類型的圖,請使用common_binscommon_norm進行試驗。
    • 例如, common_norm=True將顯示百分比作為整個人口的一部分,而False將顯示相對於組的百分比。
  • 答案中顯示的實現顯示了如何添加注釋。
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()

在此處輸入圖像描述

您可以使用norm_hist = True

文檔中:

norm_hist : bool,可選

如果為 True,則直方圖高度顯示密度而不是計數。 如果繪制了 KDE 或擬合密度,則暗示這一點。

您可以選擇一個條形圖,並設置一個以百分比定義歸一化的估計器:

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

給予:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM