Matplotlib柱状图注释添加$与千位分隔符问题求助
问题:Matplotlib水平柱状图注释添加美元符号和千位分隔符失败
我是Matplotlib新手,尝试为水平柱状图的条形注释添加美元符号($)和千位分隔符,但未能成功。以下是我的代码:
import pandas as pd from matplotlib import pyplot as plt size = df['Size'] sales_dollars = df['$ Sales'] # Figure Size fig, ax = plt.subplots(figsize =(18, 10.5)) # Horizontal Bar Plot ax.barh(size, sales_dollars) # Add padding between axes and labels ax.xaxis.set_tick_params(pad = 10) ax.yaxis.set_tick_params(pad = 10) # Add x, y gridlines ax.grid(b = True, color ='grey', linestyle ='-.', linewidth = 0.5, alpha = 0.2) # Show top values ax.invert_yaxis() ############### !Add annotation to bars! ############## for i in ax.patches: plt.text(i.get_width()+0.2, i.get_y()+0.5, str(round((i.get_width()), 2)), fontsize = 14, fontweight ='bold', color ='grey') # Add Plot Title ax.set_title('US Multi Market Sales Dollars by Item Size', loc ='center', size = 15) # Change size of tick labels plt.yticks(fontsize=14) plt.xticks(fontsize=14) # Axis Labels ax.set_xlabel('Sales Dollars', fontsize = 15) ax.set_ylabel('Size', fontsize = 15) # Get rid of scientific notation ax.get_xaxis().set_major_formatter( matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) # Show Plot plt.show()
当前代码生成的图表注释未包含所需的$和千位分隔符,恳请提供解决方法,非常感谢。
解决方案
1. 补充缺失的模块导入
你的代码中使用了matplotlib.ticker但未导入,先添加该模块:
from matplotlib import pyplot as plt from matplotlib import ticker # 新增导入
2. 修改注释的数值格式化逻辑
直接在注释循环中使用Python的f-string语法,同时实现美元符号添加和千位分隔符格式化:
############### !Add annotation to bars! ############## for i in ax.patches: # 格式化数值:保留2位小数,带千位分隔符和美元前缀 sales_value = round(i.get_width(), 2) formatted_text = f"${sales_value:,.2f}" plt.text(i.get_width()+0.2, i.get_y()+0.5, formatted_text, fontsize = 14, fontweight ='bold', color ='grey')
可选:统一x轴刻度格式
如果需要让x轴刻度也显示带美元符号的格式,可以修改x轴格式化代码:
ax.get_xaxis().set_major_formatter( ticker.FuncFormatter(lambda x, p: f"${int(x):,}"))
格式说明
f"${sales_value:,.2f}":$添加前缀,,,开启千位分隔符,.2f保留2位小数- 若销售额为整数,可改用
f"${int(sales_value):,}"去掉小数部分
内容的提问来源于stack exchange,提问作者mexicanRmy
相关产品推荐
相关产品推荐

