How to plot percentage with seaborn distplot / histplot / displot(如何使用海运dislot/histlot/dislot绘制百分比)
本文介绍了如何使用海运dislot/histlot/dislot绘制百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在dislot上绘制百分比而不是计数?
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.2seaborn.distplot替换为图形级别seaborn.displot和轴级seaborn.histplot,它们有一个stat参数。使用stat='percent'。
- 对于这两种类型的绘图,请使用
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()
按组列出的百分比
- 使用
common_norm=参数 - 参见seaborn histplot and displot output doesn't match
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()
这篇关于如何使用海运dislot/histlot/dislot绘制百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:如何使用海运dislot/histlot/dislot绘制百分比
基础教程推荐
猜你喜欢
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
