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

使用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行仍报错。

问题排查与解决

  1. 核心原因:y参数为二维列向量
    你确认的(448,)是X的形状,但y_predit_lower和y_predit_upper实际是二维列向量(形状(448,1)),而fill_between要求x和y维度完全匹配(一维对应一维)。

  2. 解决方案:将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')
    
  3. 额外修复:错误的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:05:32