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

Matplotlib中30天移动平均线折线图不显示问题排查

移动平均线折线图未显示的问题排查

我尝试绘制包含散点图、折线图的组合图表,但30天移动平均线的折线图没有显示出来。原本期望它能像下面的示例代码一样正常显示:

fig, ax = plt.subplots(figsize=(20, 6))
plt.plot(result, color='red')
plt.show()

以下是我当前的完整代码:

fig, ax = plt.subplots(figsize=(20, 10))
fig.suptitle("Performance Ratio Evolution\nFrom 2019-07-01 to 2022-03-24", fontsize=20)
plt.scatter('Date', 'PR', data=l2, label="<2", marker='D', color='#000080')
plt.scatter('Date', 'PR', data=g2l4, label="2~4", marker='D', s=15, color="#ADD8E6")
plt.scatter('Date', 'PR', data=g4l6, label="4~6", marker='D', s=15, color="#FFA500")
plt.scatter('Date', 'PR', data=g6, label=">6", marker='D', s=15, color="#964B00")
plt.plot(df['PR'].rolling(30).mean(),label='30-d moving avg of pr') # 未显示的移动平均线
plt.legend(["<2", "2~4", "4~6", ">6"])
y = [73.9 * (1 - 0.008) ** i for i in range(4)]
start_date = datetime.strptime("2019-07-01", "%Y-%m-%d")
end_date = datetime.strptime("2023-03-24", "%Y-%m-%d")
dates = []
while start_date <= end_date:
    dates.append(start_date)
    start_date += timedelta(days=365)
plt.step(dates, y, label="Performance Ratio", color="green")
plt.ylim(0, 100)
date_fmt = mdates.DateFormatter('%b/%y')
ax.xaxis.set_major_formatter(date_fmt)
ax.set_xlim([date(2019, 7, 1), date(2022, 3, 24)])
plt.ylabel("Performance Ratio (%)")
plt.legend(loc="center")
# plt.savefig("performance_ratio_evolution.png")

当前生成的图表未显示该移动平均线,请问我哪里出错了?


问题原因及修复方案

  • X轴未对齐:你的散点图通过data参数绑定了Date列作为X轴,但移动平均线仅传入了PR的滚动均值,没有对应绑定Date列。如果df的索引不是日期类型,Matplotlib会用默认的整数索引绘制,这和散点图的日期X轴完全不匹配,导致折线被绘制在图表显示范围之外。
    修复:修改移动平均线的绘制代码,同时传入日期和均值数据:

    plt.plot(df['Date'], df['PR'].rolling(30).mean(), label='30-d moving avg of pr')
    

    或者提前将df的索引设置为Date列:

    df = df.set_index('Date')
    plt.plot(df['PR'].rolling(30).mean(), label='30-d moving avg of pr')
    
  • 图例覆盖导致视觉混淆:你先给移动平均线添加了label,但随后用plt.legend(["<2", "2~4", "4~6", ">6"])手动指定图例项,直接覆盖了移动平均线的标签。之后又调用了一次plt.legend(loc="center"),虽然这不会让折线消失,但会导致你无法在图例中看到移动平均线的标识,容易误以为折线没显示。
    修复:要么删除手动指定图例的代码,让Matplotlib自动收集所有带label的元素;要么把移动平均线和绿色折线的标签加入手动列表:

    plt.legend(["<2", "2~4", "4~6", ">6", "30-d moving avg of pr", "Performance Ratio"])
    
  • 滚动均值的NaN值问题:rolling(30).mean()会生成前29个NaN值,如果这些NaN值正好占据了图表显示的起始区间,这部分折线会无法显示。
    修复:绘制前先剔除NaN值:

    plt.plot(df['Date'], df['PR'].rolling(30).mean().dropna(), label='30-d moving avg of pr')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 01:44:56