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

Matplotlib柱状图四大格式设置技术问题咨询

Matplotlib柱状图问题解决方案

1. 设置垂直网格线于柱子之间

当使用align='edge'绘制柱子时,可通过调整x轴刻度位置让网格线对齐柱子间隙:

import matplotlib.pyplot as plt
import numpy as np

labels = ['A', 'B', 'C']
x = np.arange(len(labels))
width = 0.8
ysizes_base = [10, 15, 20]
ysizes_add = [5, 7, 3]
total = [b+a for b,a in zip(ysizes_base, ysizes_add)]

fig, ax = plt.subplots()
bars = ax.bar(x, total, width, align='edge')

# 将x轴刻度移至柱子右边缘(即柱子间隙位置)
ax.set_xticks(x + width)
ax.set_xticklabels(labels)
# 开启垂直网格线,置于柱子下方
ax.grid(axis='x', linestyle='--', zorder=0)

这样网格线会精准落在相邻柱子的中间位置,不会穿过柱子。

2. 数值标签始终固定在柱子顶部

无需依赖bar_label的label_type,手动控制标签位置更可靠:

# 遍历每个柱子,在顶部添加标签
for bar in bars:
    height = bar.get_height()
    # ha='center'水平居中,va='bottom'让标签紧贴柱子顶部
    ax.text(bar.get_x() + bar.get_width()/2, height,
            f'{height}', ha='center', va='bottom', fontsize=10)

如果偏好使用bar_label,可通过padding参数调整标签与柱子的距离,确保始终在顶部:

ax.bar_label(bars, label_type='edge', padding=2, fontsize=10)

3. 调整第一个柱子左侧的边距

两种方法可灵活控制边距:

  • 方法一:使用margins设置全局边距
# x参数控制水平方向边距,数值越大边距越宽(范围0~1)
ax.margins(x=0.1)
  • 方法二:手动设置x轴范围
# 调整xlim的左边界,数值越小左侧边距越大
ax.set_xlim(-0.6, x[-1] + width + 0.2)

4. 仅显示ysizes_add的数值标签

直接调用ysizes_add数组作为标签内容即可,无需使用柱子的高度(总和):

# 手动添加标签
for bar, add_val in zip(bars, ysizes_add):
    ax.text(bar.get_x() + bar.get_width()/2, bar.get_height(),
            f'{add_val}', ha='center', va='bottom', fontsize=10)

# 或使用bar_label的labels参数
ax.bar_label(bars, labels=[str(val) for val in ysizes_add], 
             label_type='edge', padding=2, fontsize=10)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:35:21