[英]How to plot percentage with seaborn distplot / histplot / displot
seaborn 0.11.2
seaborn.distplot
替換為圖形級別seaborn.displot
和軸級別seaborn.histplot
,其中有一個stat
。 使用stat='percent'
。common_bins
和common_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()
您可以選擇一個條形圖,並設置一個以百分比定義歸一化的估計器:
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.