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

如何调整Matplotlib柱状图中X轴刻度的间距?

调整Matplotlib分组柱状图的组间距(X轴刻度间距)

问题描述

我绘制了一个分组柱状图(代码如下),但当类别数量超过3个、柱状图宽度较大时,找不到调整X轴刻度间距(即柱状图组之间间距)的方法。普通的X轴刻度间距调整方案并不适用于这种分组柱状图场景,请问该如何解决?

原始代码:

# data from https://allisonhorst.github.io/palmerpenguins/

import matplotlib.pyplot as plt
import numpy as np

species = ("Adelie", "Chinstrap", "Gentoo")
penguin_means = {
    'Bill Depth': (18.35, 18.43, 14.98),
    'Bill Length': (38.79, 48.83, 47.50),
    'Flipper Length': (189.95, 195.82, 217.19),
}

x = np.arange(len(species))  # the label locations
width = 0.25  # the width of the bars
multiplier = 0

fig, ax = plt.subplots(layout='constrained')

for attribute, measurement in penguin_means.items():
    offset = width * multiplier
    rects = ax.bar(x + offset, measurement, width, label=attribute)
    ax.bar_label(rects, padding=3)
    multiplier += 1

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Length (mm)')
ax.set_title('Penguin attributes by species')
ax.set_xticks(x + width, species)
ax.legend(loc='upper left', ncols=3)
ax.set_ylim(0, 250)

plt.show()

解决方案

分组柱状图的组间距核心由x数组的元素间隔控制,直接修改x的生成逻辑即可实现组间距调整,具体步骤如下:

  • 扩大组基础间隔:将x = np.arange(len(species))改为带缩放系数的生成方式,比如x = np.arange(len(species)) * 1.5(系数越大,组间距越大)。
  • 修正刻度位置:因为每组有多个柱子,刻度需要放在组的正中间,所以ax.set_xticks的位置要调整为x + width*(len(penguin_means)-1)/2(len(penguin_means)是每组的柱子数量)。
  • 可选:调整X轴范围:如果组间距扩大后边缘柱子被截断,可以手动设置X轴范围,避免显示问题。

修改后的完整代码(关键修改处已标注):

import matplotlib.pyplot as plt
import numpy as np

species = ("Adelie", "Chinstrap", "Gentoo", "NewSpecies1", "NewSpecies2")  # 增加测试类别
penguin_means = {
    'Bill Depth': (18.35, 18.43, 14.98, 17.2, 16.8),
    'Bill Length': (38.79, 48.83, 47.50, 40.1, 42.3),
    'Flipper Length': (189.95, 195.82, 217.19, 192.5, 198.7),
}

# --- 关键修改1:扩大组基础间隔 ---
group_gap = 1.5  # 组间距系数,可根据需求调整
x = np.arange(len(species)) * group_gap  
width = 0.25  # 柱子宽度可保持不变或按需调整
multiplier = 0

fig, ax = plt.subplots(layout='constrained')

for attribute, measurement in penguin_means.items():
    offset = width * multiplier
    rects = ax.bar(x + offset, measurement, width, label=attribute)
    ax.bar_label(rects, padding=3)
    multiplier += 1

ax.set_ylabel('Length (mm)')
ax.set_title('Penguin attributes by species')

# --- 关键修改2:修正刻度到组中间 ---
num_bars_per_group = len(penguin_means)
ax.set_xticks(x + width*(num_bars_per_group-1)/2, species)

# --- 可选:调整X轴范围,避免边缘柱子截断 ---
ax.set_xlim(-width, x[-1] + width*num_bars_per_group)

ax.legend(loc='upper left', ncols=3)
ax.set_ylim(0, 250)

plt.show()

原理说明

分组柱状图的每组柱子是基于x的位置进行偏移绘制的,x数组中相邻元素的差值就是组与组之间的基础间距。普通的刻度间距调整方法针对的是连续数值轴,而分组柱状图的X轴是离散的类别轴,所以直接调整x的间隔才是最直接有效的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 09:46:40