You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Power BI中Python代码的柱状图百分比显示异常问题?

问题解决:Power BI中Python柱状图百分比显示异常修复

核心问题原因

mticker.PercentFormatter()默认会将输入数值乘以100后添加百分号,比如数值74会被转换成7400%。但你的数据表中Today字段已经是百分比的整数形式(如74代表74%),直接使用默认格式化会导致倍数错误。

修复后的完整代码

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np

numbers1 = dataset.loc[0:36, 'Today'].tolist()
numbers2 = dataset.loc[0:36, 'Tomorrow'].tolist()
names = dataset.loc[0:36, 'Cities'].tolist()

data = list(zip(names, numbers1, numbers2))
data.sort(key=lambda x: x[1], reverse=True)
sorted_names, sorted_numbers1, sorted_numbers2 = zip(*data)

fig, ax = plt.subplots(figsize=(12, 6))

width = 0.4
spacing = 0.1

x = np.arange(len(sorted_names))

rects1 = ax.bar(x - spacing/2, sorted_numbers1, width, color='blue')

# 按数值大小设置柱子颜色
for i in range(len(sorted_names)):
    if sorted_numbers1[i] < sorted_numbers2[i]:
        rects1[i].set_color('green')
    elif sorted_numbers1[i] > sorted_numbers2[i]:
        rects1[i].set_color('red')

ax.set_xticks(x)
ax.set_xticklabels(sorted_names, rotation=45, ha='right')

# 修复y轴百分比格式:指定最大值为100,避免自动放大100倍
ax.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=100))
# 强制y轴显示整数刻度
ax.yaxis.set_major_locator(mticker.MaxNLocator(integer=True))

# 修复柱顶文本:确保显示整数百分比
for i, rect in enumerate(rects1):
    height = rect.get_height()
    ax.text(rect.get_x() + rect.get_width() / 2, height, f'{int(sorted_numbers1[i])}%', ha='center', va='bottom')

plt.subplots_adjust(bottom=0.4, wspace=0.5, hspace=0.5)

plt.show()

关键修改点

  • y轴格式化修复:给PercentFormatter添加xmax=100参数,明确数值最大值对应100%,让74直接显示为74%。
  • y轴整数刻度:用MaxNLocator(integer=True)强制y轴只显示整数刻度,避免出现小数百分比。
  • 柱顶文本优化:用int()转换数值,确保显示整数形式的百分比,防止浮点型数值(如74.0)显示成74.0%。

内容的提问来源于stack exchange,提问作者Алейна Дарк

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 08:47:44