簡體   English   中英

如何將數據標簽添加到seaborn countplot / factorplot

[英]how to add data Labels to seaborn countplot / factorplot

我使用 python3,seaborn countplot,我的問題:

  1. 如何為每個條添加計數值? 在每個欄的頂部顯示標簽?
  2. 如何按降序排列這些條?

我是這樣寫的:

fig = plt.figure(figsize=(10,6))
sns.countplot(data_new['district'],data=data_new)
plt.show()

在此處輸入圖片說明

非常感謝 !

我使用了我生成的一個簡單示例數據,但您可以將 df 名稱和列名稱替換為您的數據:

ax = sns.countplot(df["coltype"], 
                   order = df["coltype"].value_counts().index)

for p, label in zip(ax.patches, df["coltype"].value_counts().index):
    ax.annotate(label, (p.get_x()+0.375, p.get_height()+0.15))

這會產生: 在此處輸入圖片說明

您可能會稍微調整一下該位置以使其看起來更好。

我知道這是一個老問題,但我想如何標記seaborn.countplotmatplotlib.pyplot.bar比之前的答案更簡單一些(使用 matplotlib-3.4.2 和 seaborn-0.11.1 測試) .

使用絕對值:

ax = sns.countplot(x=df['feature_name'],
                   order=df['feature_name'].value_counts(ascending=False).index);

abs_values = df['feature_name'].value_counts(ascending=False).values

ax.bar_label(container=ax.containers[0], labels=abs_values)

例子: 圖片1

絕對值和相對值:

ax = sns.countplot(x=df['feature_name'],
                   order=df['feature_name'].value_counts(ascending=False).index);
        
abs_values = df['feature_name'].value_counts(ascending=False)
rel_values = df['feature_name'].value_counts(ascending=False, normalize=True).values * 100
lbls = [f'{p[0]} ({p[1]:.0f}%)' for p in zip(abs_values, rel_values)]

ax.bar_label(container=ax.containers[0], labels=lbls)

例子: 圖片2

檢查這些鏈接:

  1. https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bar_label.html
  2. https://matplotlib.org/stable/api/container_api.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM