- 截至
seaborn 0.11.2
- 对于这两种类型的绘图,请使用
common_bins 和common_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()