如何将Python图表Y轴标签设为单引号千分位适配Power BI
解决Matplotlib图表Y轴瑞士式单引号千分位分隔符问题
要把Matplotlib图表Y轴的千分位分隔符从逗号改成瑞士常用的单引号(例如100'000),可以通过自定义格式化函数实现,以下是具体修改方案:
核心修改思路
替换原代码中使用逗号分隔的格式化逻辑,改用自定义函数将数字格式化为单引号分隔的形式。
修改后的完整代码
import matplotlib.pyplot as plt import numpy as np import matplotlib.font_manager as font_manager import matplotlib as mpl from matplotlib.ticker import FuncFormatter # 新增导入 # 自定义瑞士千分位格式化函数 def swiss_number_format(x, pos): # 先按逗号格式化,再替换逗号为单引号 return f"{x:,.0f}".replace(',', "'") labels = dataset.cat x = np.arange(len(labels)) # the label locations width = 0.35 fig, ax = plt.subplots(figsize=(45, 15)) ax2 = ax.twinx() rects3 = ax2.bar(x + width/2, dataset.revenue, width, color='#FFB700', label='revenue') rects1 = ax.bar(x - width/2, dataset.ord, width, color='#00A1E4', label='east') rects2 = ax.bar(x - width/2, dataset.bag, width, color='#D9D9D9', label='west', bottom=dataset.ord,) ax.set_xticks(x) ax.set_xticklabels(labels) ax.yaxis.set_tick_params(pad=5) ax.yaxis.set_label_coords(-0.03, 0.5) ax2.yaxis.set_label_coords(1.07, 0.5) ax.xaxis.set_tick_params(pad=7) # 替换原格式化代码为自定义函数 ax2.yaxis.set_major_formatter(FuncFormatter(swiss_number_format)) # 如果需要给左侧Y轴(ax)也应用同样格式,添加下面一行 # ax.yaxis.set_major_formatter(FuncFormatter(swiss_number_format)) plt.show()
关键修改点
- 新增导入
FuncFormatter,用于自定义格式化逻辑 - 定义
swiss_number_format函数:先将数字格式化为带逗号的千分位字符串,再把逗号替换为单引号 - 将原有的
StrMethodFormatter替换为FuncFormatter(swiss_number_format),应用自定义格式
如果需要给左侧Y轴(ax)也使用相同的单引号分隔格式,只需添加注释里的那行代码即可。
内容的提问来源于stack exchange,提问作者reo
相关产品推荐
相关产品推荐

