如何使用条形标签的fmt选项将%添加到批注

2024-10-03 09:07:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Matplotlib中使用新的bar_标签选项,但找不到在标签值后附加文本的方法,例如“%”。以前,使用ax.text我可以使用f-strings,但我找不到将f-strings与条形标签方法结合使用的方法

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()

Tags: to方法textmatplotlibbarplt标签ax
1条回答
网友
1楼 · 发布于 2024-10-03 09:07:21

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

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

相关问题 更多 >