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

Matplotlib中X轴分组优化:标签居中与方法分隔问题求解

解决Matplotlib柱状图的三个布局问题

我用Matplotlib绘制图表,通过两种方法处理两个数据集并调整拟合类型,得到8个结果数据点。现有代码生成的图表存在三个问题:

  • 数据集标签及X轴刻度未居中对应两组柱状图
  • 方法标签位置未精准居中
  • 需要添加垂直分隔线区分不同方法组

原始代码

import numpy as np
import matplotlib.pyplot as plt

n_groups = 4
means_type1 = (10,20,10,15)
means_type2 = (20,30,15,10)

# create plot
fig, ax = plt.subplots()
plt.grid(which='major', color='#EEEEEE', linewidth=0.5,zorder=0)
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8

rects1 = plt.bar(index, means_type1, bar_width,
alpha=1,
color='blue',
label='Type 1',zorder=3)

rects2 = plt.bar(index + bar_width, means_type2, bar_width,
alpha=1,
color='green',
label='Type 2',zorder=3)

plt.ylabel('Metric')
plt.xticks(index + bar_width, ('Dataset 1', 'Dataset 2', 'Dataset 1', 'Dataset 2'))
plt.legend()
plt.figtext(0.4,0.01, "Method 1", ha="center", va="center",fontsize=7)
plt.figtext(0.77,0.01, "Method 2", ha="center", va="center",fontsize=7)

plt.tight_layout()
plt.show()

原始图表效果

原始图表


修改后的代码

import numpy as np
import matplotlib.pyplot as plt

n_groups = 4
means_type1 = (10,20,10,15)
means_type2 = (20,30,15,10)

# 创建画布和轴
fig, ax = plt.subplots()
plt.grid(which='major', color='#EEEEEE', linewidth=0.5, zorder=0)
index = np.arange(n_groups)
bar_width = 0.35

# 绘制两组柱状图
rects1 = plt.bar(index, means_type1, bar_width, alpha=1, color='blue', label='Type 1', zorder=3)
rects2 = plt.bar(index + bar_width, means_type2, bar_width, alpha=1, color='green', label='Type 2', zorder=3)

# 设置Y轴标签
plt.ylabel('Metric')

# 1. 修正X轴刻度位置,让标签居中对应每组两个柱状图
tick_positions = index + bar_width / 2  # 取两组柱子的中间位置作为刻度点
plt.xticks(tick_positions, ('Dataset 1', 'Dataset 2', 'Dataset 1', 'Dataset 2'))

# 添加图例
plt.legend()

# 2. 精准设置方法标签位置,基于轴坐标而非画布比例
method1_center = (tick_positions[0] + tick_positions[1]) / 2
method2_center = (tick_positions[2] + tick_positions[3]) / 2
# 使用ax.text基于轴坐标定位,确保居中
ax.text(method1_center, -2, "Method 1", ha="center", va="center", fontsize=7)
ax.text(method2_center, -2, "Method 2", ha="center", va="center", fontsize=7)

# 3. 添加垂直分隔线,区分不同方法组
# 分隔线位于第二组和第三组数据之间的空隙处
divider_position = tick_positions[1] + bar_width
ax.axvline(x=divider_position, color='#CCCCCC', linestyle='--', linewidth=1)

# 调整布局,避免标签被截断
plt.tight_layout()
plt.show()

关键修改说明

  • 修正X轴刻度居中:将刻度位置从index + bar_width改为index + bar_width/2,让每个刻度标签正好对应同一数据集的两个柱子中间位置。
  • 精准定位方法标签:放弃基于画布比例的figtext,通过计算每组方法的轴坐标中心,用ax.text定位,确保标签始终在对应方法组正下方,不受画布大小影响。
  • 添加方法组分隔线:计算两组方法之间的空隙位置,用ax.axvline绘制垂直虚线,清晰区分不同方法的结果区域。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 12:55:23