有没有一种方法可以在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();
发布于 2021-08-19 15:44:30
从
seaborn.distplot
开始的stat
参数的Figure level seaborn.displot
和Axes seaborn.histplot
。使用stat='percent'
.common_bins
和common_norm
。common_norm=True
将显示百分比作为整个总体的一部分,而False
将显示相对于group.的百分比
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()
按组列出的百分比
使用parameter
common_norm=
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()
发布于 2020-08-12 17:12:15
发布于 2020-08-12 17:16:18
您可以选择条形图,并设置以百分比定义归一化的估计器:
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()
给予:
https://stackoverflow.com/questions/63373194
复制相似问题