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

Matplotlib绘图报错:x与y首维度不匹配((5,)和(4,))求解决

解决Matplotlib中x和y维度不匹配的ValueError

问题根源

你定义的mengde数组包含5个元素([0,1,2,3,4]),但y_snitt仅存4个均值(对应浓度0、1、2、4的样本统计值),两者首维度长度不一致,触发Matplotlib的维度校验错误。

修复步骤

  1. 修正mengde数组,仅保留与y_snitt对应的浓度值,移除多余的3
  2. 同步修正vlines函数的x轴参数,确保与y轴数据长度完全匹配

修改后的完整代码

from pylab import*

# Leser inn lengden av REM-søvn for de ulike konsentrasjonenen med etanol
y_0 = array([88.6, 73.2, 91.4, 68.0, 75.2])
y_1 = array([63.0, 53.9, 69.2, 50.1, 71.5])
y_2 = array([44.9, 59.5, 40.2, 56.3, 38.7])
y_4 = array([31.0, 39.6, 45.3, 25.2, 22.7])

# Bestemmer gj.nsitt, standaravik og standarfeil for de fire konsentrasjonene
y_snitt = array([mean(y_0), mean(y_1), mean(y_2), mean(y_4)])
y_stav = array([std(y_0,ddof=1), std(y_1,ddof=1), std(y_2,ddof=1), std(y_4,ddof=1)])
SE = y_stav/sqrt(5)

# Skriv ut gj.nsitt, standaravik og standardfeil
print("Gjennomsnitt", around(y_snitt,2))
print("Standarfeil", around(SE,2))

# Plottr gj.snitt med feilmarginer
# 修正mengde数组,只保留对应4个浓度的x值
mengde = array([0, 1, 2, 4])
plot(mengde, y_snitt,"bo")
vlines(mengde, y_snitt-2*SE, y_snitt+2*SE,"red")
ylabel("REM-søvn (min)")

x = linspace(0, 4, 100)
y = 77.30 * 0.803**x
plot(x, y, "--")
show()

额外说明

如果实验中确实存在浓度为3的样本,需补充对应的y_3数据数组,并同步更新y_snitt、y_stav等统计数组,确保所有x轴数据与y轴统计值一一对应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:05:32