如何使用 bar_label 的 fmt 选项向注释添加 %

问题描述 投票:0回答:2

我正在尝试使用 Matplotlib 中的新 bar_label 选项,但无法找到附加文本的方法,例如标签值后的“%”。以前,使用 ax.text 我可以使用 f 字符串,但我找不到通过 bar-label 方法使用 f 字符串的方法。

fig, ax = plt.subplots(1, 1, figsize=(12,8))
hbars = ax.barh(wash_needs.index, wash_needs.values, color='#2a87c8')
ax.tick_params(axis='x', rotation=0)

# previously I used this approach to add labels 
#for i, v in enumerate(wash_needs):
#    ax.text(v +3, i, str(f"{v/temp:.0%}"), color='black', ha='right', va='center')

ax.bar_label(hbars, fmt='%.2f', padding=3) # this adds a label but I can't find a way to append a '%' after the number
    
plt.show()
python matplotlib bar-chart
2个回答
14
投票

我找到了一种将“%”附加到标签数字的方法 - 添加一个额外的“%%

ax.bar_label(hbars, fmt='%.2f%%', padding=3)

工作示例

import pandas as pd
import seaborn as sns  # for tips data

tips = sns.load_dataset('tips').loc[:15, ['total_bill', 'tip']]
tips.insert(2, 'tip_percent', tips.tip.div(tips.total_bill).mul(100).round(2))

   total_bill   tip  tip_percent
0       16.99  1.01         5.94
1       10.34  1.66        16.05
2       21.01  3.50        16.66
3       23.68  3.31        13.98
4       24.59  3.61        14.68

# plot
ax = tips.plot(kind='barh', y='tip_percent', legend=False, figsize=(12, 8))
labels = ax.set(xlabel='Tips: Percent of Bill (%)', ylabel='Record', title='Tips % Demo')
annotations = ax.bar_label(ax.containers[0], fmt='%.2f%%', padding=3)
ax.margins(x=0.1)

enter image description here


0
投票

ax.bar_label() 中还有一个 labels 参数,允许您设置标签格式。但是,请注意,如果您提供标签输入,fmt 参数将对最终输出没有影响。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.