使用matplotlib fill_between绘制置信带时遇维度不匹配错误
解决matplotlib fill_between维度不匹配错误
问题描述
使用matplotlib.pyplot.fill_between绘制置信带时触发错误:
ValueError: x and y must have same first dimension, but have shapes (1,) and (448, 1)
相关代码片段:
plt.xlim([0, 45.5]) plt.ylim([-16.50, 15.000]) plt.plot(len(X)-1, y_predicted, 'b', linewidth=1) plt.fill_between(X, y_predit_lower, y_predit_upper, alpha=0.1, color='green') plt.plot(X, y_predit_upper, 'g', linewidth=1, linestyle='--') plt.plot(X, y_predit_lower, 'g', linewidth=1, linestyle='--') # 其余绘图代码... plt.show()
其中X是从DataFrame提取的一维numpy数组(形状(448,)),但fill_between行仍报错。
问题排查与解决
核心原因:y参数为二维列向量
你确认的(448,)是X的形状,但y_predit_lower和y_predit_upper实际是二维列向量(形状(448,1)),而fill_between要求x和y维度完全匹配(一维对应一维)。解决方案:将y数组转为一维
在调用fill_between前,用.flatten()或.squeeze()把y数组转为一维:# 转换为一维数组 y_predit_lower = y_predit_lower.flatten() y_predit_upper = y_predit_upper.flatten() # 再调用fill_between plt.fill_between(X, y_predit_lower, y_predit_upper, alpha=0.1, color='green')额外修复:错误的plot调用
代码中plt.plot(len(X)-1, y_predicted, 'b', linewidth=1)存在逻辑错误:len(X)-1是单个标量值,若y_predicted是数组,这行只会在x=447的位置绘制所有y点,正确做法是用X作为x轴数据:plt.plot(X, y_predicted, 'b', linewidth=1)
内容的提问来源于stack exchange,提问作者Emc101
相关产品推荐
相关产品推荐

