【问题标题】:How to annotate horizontal bar plots with count and percent如何用计数和百分比注释水平条形图
【发布时间】:2022-01-05 09:17:01
【问题描述】:

如何获得每个条右侧的计数和百分比???目前我只知道如何计算。

import pandas as pd
import matplotlib.pyplot as plt

age = ['0-17','18-60','61-80']

df3 = pd.DataFrame(data={'Male':[82,550,25], 'Female':[72,309,7]}, index=age)
print(df3)

ax = df3.plot(kind='barh', ylabel='Age', title='Passenger Count by Age and Sex')
ax.set(xlabel='No. of Passengers')

for c in ax.containers:
    # set the bar label
    ax.bar_label(c, fmt='%.0f', label_type='edge')

ax.legend(title='Sex', bbox_to_anchor=(1, 1.02), loc='upper left')

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)



plt.show()

【问题讨论】:

标签: python pandas matplotlib annotations bar-chart


【解决方案1】:

函数bar_label 接受参数label=,其中包含要使用的标签列表。可以通过循环遍历数据框来创建字符串列表。

请参阅此answer 以获得对该功能的详细说明和更多示例。

以下示例代码使用 100% 表示所有乘客:

import pandas as pd
import matplotlib.pyplot as plt

age = ['0-17', '18-60', '61-80']

df3 = pd.DataFrame(data={'Male': [82, 550, 25], 'Female': [72, 309, 7]}, index=age)

ax = df3.plot(kind='barh', ylabel='Age', title='Passenger Count by Age and Sex')
ax.set(xlabel='No. of Passengers')

total = sum(df3.sum())
for c, col in zip(ax.containers, df3.columns):
    ax.bar_label(c, label_type='edge', labels=[f'{val}\n{val / total * 100.0:.1f} %' for val in df3[col]])

ax.legend(title='Sex', bbox_to_anchor=(1, 1.02), loc='upper left')

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

plt.tight_layout()
plt.show()

  • 如果条形值为 0,则以下选项会添加一个条件以包含空白字符串。
    • 赋值表达式 (:=) 可用于 python 3.8
ax = df3.plot(kind='barh', ylabel='Age', title='Passenger Count by Age and Sex', width=0.75)
ax.set(xlabel='No. of Passengers')

tot = df.sum().sum()

# 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/tot*100:0.1f}%\n{w}' if (w := v.get_width()) > 0 else '' for v in c]
    
    ax.bar_label(c, labels=labels, label_type='edge', padding=0.3)
    
ax.margins(x=0.15)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 2021-10-21
    • 2017-08-09
    • 2016-03-21
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    相关资源
    最近更新 更多