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

Matplotlib柱状图文本位置异常求助:文本挤压至侧边

分组柱状图文本位置错误问题及解决方案

绘制Matplotlib分组柱状图时,百分比文本被挤压至侧边无法对应柱子顶部,核心原因是文本标注时误用了自定义x轴标签值,而非柱子实际的x轴位置。

解决步骤:

  • 三组柱子的实际x轴位置分别是i - width、i、i + width(i为索引),文本标注时需对应这些位置,而非labels里的数值
  • 添加va='bottom'参数让文本在柱子顶部上方显示,避免和柱子重叠
  • 格式化百分比文本,保留两位小数提升可读性

修改后的完整代码:

import matplotlib.pyplot as plt

# 定义数据
high_values = [4, 1, 3, 1, 1, 0.0, 5, 2, 3, 13, 21, 61, 69, 77, 74, 49, 35, 25, 14, 9, 9, 20]
low_values = [29, 6, 6, 11, 15, 24, 45, 38, 47, 78, 68, 47, 46, 16, 11, 3, 2, 1, 2, 0.0, 0.0, 1]
close_values = [17, 4, 8, 8, 10, 7, 16, 22, 24, 44, 52, 53, 41, 51, 46, 31, 16, 18, 6, 4, 4, 14]

# 定义百分比
high_percentages = [0.8, 0.2, 0.6, 0.2, 0.2, 0.0, 1.01, 0.4, 0.6, 2.62, 4.23, 12.27, 13.88, 15.49, 14.89, 9.86, 7.04, 5.03, 2.82, 1.81, 1.81, 4.02]
low_percentages = [5.84, 1.21, 1.21, 2.21, 3.02, 4.83, 9.05, 7.65, 9.46, 15.69, 13.68, 9.46, 9.26, 3.22, 2.21, 0.6, 0.4, 0.2, 0.4, 0.0, 0.0, 0.2]
close_percentages = [3.42, 0.8, 1.61, 1.61, 2.01, 1.41, 3.22, 4.43, 4.83, 8.85, 10.46, 10.66, 8.25, 10.26, 9.26, 6.24, 3.22, 3.62, 1.21, 0.8, 0.8, 2.82]

# x轴标签
labels = [-2.76, -2.5, -2.25, -2.0, -1.75, -1.5, -1.25, -1.0, -0.75, -0.5, -0.25, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.76]

width = 0.2
x = range(len(labels))

plt.figure(figsize=(11,5))

# 绘制三组柱子
high_bars = plt.bar([i - width for i in x], high_values, width, color="green", label="High")
low_bars = plt.bar([i for i in x], low_values, width, color="red", label="Low")
close_bars = plt.bar([i + width for i in x], close_values, width, color="blue", label="Close")

# 设置x轴刻度
plt.xticks(x, labels)
plt.xlabel("Percentage")
plt.ylabel('Number Of Times')
# 注意:start_date和end_date需提前定义,这里假设已定义
plt.title(f'High, Low, and Close Values from {start_date} to {end_date}')
plt.legend()

# 标注High柱子的百分比文本
for i, (y, p) in enumerate(zip(high_values, high_percentages)):
    plt.text(i - width, y, f"{p:.2f}", color="red", va='bottom', ha='center')

# 标注Low柱子的百分比文本
for i, (y, p) in enumerate(zip(low_values, low_percentages)):
    plt.text(i, y, f"{p:.2f}", color="green", va='bottom', ha='center')

# 标注Close柱子的百分比文本
for i, (y, p) in enumerate(zip(close_values, close_percentages)):
    plt.text(i + width, y, f"{p:.2f}", color="blue", va='bottom', ha='center')

plt.show()

关键修改点:

  1. 文本的x坐标从labels改为i - width/i/i + width,与对应柱子的位置完全对齐
  2. 添加ha='center'确保文本水平居中于柱子上方
  3. 使用f"{p:.2f}"格式化百分比文本,保留两位小数
  4. 给每组柱子添加label参数,让图例显示正确名称

内容的提问来源于stack exchange,提问作者Shajman Faiz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:07:16