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

如何用Matplotlib实现目标样式的分组水平短线图表?

问题描述

当前使用以下Matplotlib代码生成图表:

plt.figure()
plt.axhline(y=6, xmin=0.1-0.05, xmax=0.1+0.05, color='r', linewidth=2, label='Apple')
plt.axhline(y=5, xmin=0.22-0.05, xmax=0.22+0.05, color='b', linewidth=2, label='Grape')

plt.axhline(y=3, xmin=0.4-0.05, xmax=0.4+0.05, color='r', linewidth=2, label='Apple')
plt.axhline(y=2, xmin=0.52-0.05, xmax=0.52+0.05, color='b', linewidth=2, label='Grape')

plt.legend()
plt.show()

生成的图表:
当前生成的图表

希望绘制出目标样式的图表:
目标样式图表

请问实现该目标图表的正确绘图方式是什么?


实现方案

原代码通过axhline手动计算x范围的方式容易出现对齐偏差,且维护性差。以下是两种更可靠的实现方式:

方法1:使用barh绘制横向条形图(推荐)

目标图表本质是分组横向短条,用横向条形图可精准控制分组与对齐:

import matplotlib.pyplot as plt

# 数据与配置
groups = ['Group 1', 'Group 2']
apple_vals = [6, 3]
grape_vals = [5, 2]
bar_width = 0.35
group_pos = range(len(groups))

plt.figure()
# 绘制Apple分组条形
plt.barh([p - bar_width/2 for p in group_pos], apple_vals, height=bar_width, color='r', label='Apple')
# 绘制Grape分组条形
plt.barh([p + bar_width/2 for p in group_pos], grape_vals, height=bar_width, color='b', label='Grape')

# 配置轴标签与图例
plt.yticks(group_pos, groups)
plt.ylabel('分组')
plt.xlabel('数值')
plt.legend()
plt.show()

方法2:用axvline固定位置绘制线条

若偏好线条样式,可通过固定x轴位置替代手动计算范围:

import matplotlib.pyplot as plt

plt.figure()
group_x = [1, 2]  # 两个分组的x轴基准位置
line_len = 0.3     # 线条纵向长度比例

# 第一组
plt.axvline(x=group_x[0], ymin=(6 - line_len/2)/7, ymax=(6 + line_len/2)/7, color='r', linewidth=2)
plt.axvline(x=group_x[0]+0.2, ymin=(5 - line_len/2)/7, ymax=(5 + line_len/2)/7, color='b', linewidth=2)
# 第二组
plt.axvline(x=group_x[1], ymin=(3 - line_len/2)/7, ymax=(3 + line_len/2)/7, color='r', linewidth=2)
plt.axvline(x=group_x[1]+0.2, ymin=(2 - line_len/2)/7, ymax=(2 + line_len/2)/7, color='b', linewidth=2)

# 配置轴刻度与图例
plt.xticks([1.1, 2.1], ['Group 1', 'Group 2'])
plt.legend(['Apple', 'Grape'])
plt.ylim(0,7)
plt.show()

说明

  • 方法1是贴合目标样式的标准实现,自动处理对齐逻辑,后续修改数据更便捷;
  • 方法2延续了原代码的线条思路,通过固定x位置避免了手动计算的误差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:10:28