我的目標是在 y 軸上創建帶有計數的條形圖,并用組的百分比標記條形圖。下面的代碼讓我走到了一半 -
import seaborn as sns
from itertools import product
titanic = sns.load_dataset("titanic")
features = ['sex', 'class', 'who', 'adult_male']
n = 1
plt.figure(figsize=[12, 14])
for f in features:
plt.subplot(3, 2, n)
ax = sns.countplot(x=f, hue='survived', edgecolor='black', alpha=0.8, data=titanic)
sns.despine()
plt.title("Countplot of {} by alive".format(f))
n=n 1
plt.tight_layout()
for c in ax.containers:
labels = [f'{h/titanic.survived.count()*100:0.1f}%' if (h := v.get_height()) > 0 else '' for v in c]
ax.bar_label(c,labels=labels, label_type='edge')

問題是百分比不正確。例如,在“幸存者性別計數圖”圖表中,男性百分比是計算整個資料集中“0”類男性的百分比。
如何調整我的代碼以計算男性類別中“0”類男性的百分比?所以男性類別中的藍色條應該是 81%,橙色條應該是 19%。
uj5u.com熱心網友回復:
手動生成特征內比例,例如對于特征sex:
- 計算
survived每個sex使用的比例
Full example with all features:
titanic = sns.load_dataset('titanic') features = ['sex', 'class', 'who', 'adult_male'] hue = 'survived' fig, axs = plt.subplots(2, 2, figsize=(10, 10), constrained_layout=True) for feat, ax in zip(features, axs.ravel()): # group ordering differs by dtype col = titanic[feat] if col.dtype == 'category': groups = col.cat.categories elif col.dtype == 'bool': groups = [False, True] else: groups = col.unique() # within-feature proportions proportions = titanic.groupby(feat)[hue].value_counts(normalize=True) sns.countplot(x=feat, hue=hue, edgecolor='k', alpha=0.8, data=titanic, ax=ax) ax.set_title(f'Countplot of ${feat}$ by ${hue}$') sns.despine() # retrieve proportions by the container's label (hue) and group (feature) for c in ax.containers: labels = [f'{proportions.loc[g, int(c.get_label())]:.1%}' for g in groups] ax.bar_label(c, labels)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/447244.html標籤:Python matplotlib 海运 分组条形图
上一篇:如何用字串制作多行標題
下一篇:繪圖:x必須是標簽或位置
