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

如何用Matplotlib Python实现目标多X轴柱状图?现有代码未达预期

问题描述

我想要制作出目标图表(参考图:https://i.sstatic.net/xQZar.png),目前尝试了以下代码,但生成的图表和预期差距很大,不知道怎么调整:

import matplotlib.pyplot as plt
import numpy as np 

X = ['Class 1','Class 2','Class 3','Class 4', 'Class 5', 'Class 6', 'Class 7'] 

sE = ['-9,51', '-13,5', '0,193', '9,564', '23,13', '-0,252', '-0,442']
s = ['19,605', '28,388', '1,762', '-4,264', '-24,716', '-26,956', '0,382']
eE = ['-5,364', '-7,954', '-3,756', '-0,184', '1,883', '41,876', '-0,012']


X_axis = np.arange(len(X)) 

# plt.bar(X_axis, sE, color='red',width = 0.25, edgecolor='black') 
# plt.bar(X_axis+0.25, s, color='cyan',width = 0.25, edgecolor='black') 
# plt.bar(X_axis+0.5, eE, color='green',width = 0.25, edgecolor='black') 

#plt.hist([sE, s, eE], color = ['red', 'cyan', 'green'], edgecolor = 'black', histtype = 'bar')

#plt.xticks(X_axis, X) 
plt.xlabel("Classes")  
plt.title("Geographical STP A") 
plt.show() 
解决方案

你的代码核心问题是数据格式错误(字符串+逗号小数点),且分组条形图的逻辑未正确启用。以下是修正后的完整代码:

import matplotlib.pyplot as plt
import numpy as np 

# 类别名称
X = ['Class 1','Class 2','Class 3','Class 4', 'Class 5', 'Class 6', 'Class 7'] 

# 转换数据格式:替换逗号为小数点,转成数值类型
sE = np.array([float(val.replace(',', '.')) for val in ['-9,51', '-13,5', '0,193', '9,564', '23,13', '-0,252', '-0,442']])
s = np.array([float(val.replace(',', '.')) for val in ['19,605', '28,388', '1,762', '-4,264', '-24,716', '-26,956', '0,382']])
eE = np.array([float(val.replace(',', '.')) for val in ['-5,364', '-7,954', '-3,756', '-0,184', '1,883', '41,876', '-0,012']])

X_axis = np.arange(len(X)) 
bar_width = 0.25

# 绘制三组不重叠的条形图
plt.bar(X_axis - bar_width, sE, color='red', width=bar_width, edgecolor='black', label='sE')
plt.bar(X_axis, s, color='cyan', width=bar_width, edgecolor='black', label='s')
plt.bar(X_axis + bar_width, eE, color='green', width=bar_width, edgecolor='black', label='eE')

# 设置x轴刻度居中在每组条形上方
plt.xticks(X_axis, X)
plt.xlabel("Classes")  
plt.title("Geographical STP A")
# 添加图例区分三组数据
plt.legend()
# 可选:添加y轴网格,提升可读性
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()

关键调整说明:

  • 数据转换:将带逗号小数点的字符串转为matplotlib可识别的数值类型,这是绘图的基础
  • 条形位置优化:通过偏移bar_width让三组条形不重叠,保证每个类别下的三个数据都能清晰展示
  • 细节完善:添加图例、调整刻度位置,同时matplotlib会自动处理负数值的向下延伸展示,匹配目标图表逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 08:14:53