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

Streamlit中如何叠加显示两个散点折线图?

实际行情与NeuralProphet预测结果叠加实现方案

多次调用st.plotly_chart()会渲染独立图表,无法实现叠加效果。NeuralProphet自带的绘图方法返回原生Plotly Figure对象,支持直接追加数据轨迹实现同图展示,以下是可直接运行的修正方案。


修正后完整代码

import streamlit as st
from datetime import date

import yfinance as yf
from neuralprophet import NeuralProphet

from plotly import graph_objs as go

START = "2015-01-01"
TODAY = date.today().strftime("%Y-%m-%d")

st.title("Stock Price Prediction")

stocks = ("AAPL", "GOOG", "MSFT", "GME", "TSLA", "RIVN")
selected_stocks = st.selectbox("Select Dataset for Prediction", stocks)

n_years = st.slider("Years of Prediction:", 1, 10)
period = n_years * 365

# 适配新版Streamlit缓存规则,替换已弃用的st.cache
@st.cache_data
def load_data(ticker):
    data = yf.download(ticker, START, TODAY)
    data.reset_index(inplace=True)
    return data

data_load_state = st.text("Load data...")
data = load_data(selected_stocks)
data_load_state.text("Loading data...done!")

st.subheader('Raw Data')
st.write(data.tail())

# 模型训练与预测
df_train = data[['Date', 'Close']]
df_train = df_train.rename(columns={"Date": "ds", "Close": "y"})

m = NeuralProphet()
metrics = m.fit(df_train)
future = m.make_future_dataframe(df=df_train, periods=period)
forecast = m.predict(df=future)

st.subheader('Forecast data')
st.write(forecast.tail())

# 同图叠加实际数据与预测结果
st.write('Actual Price vs Forecast Result')
# 先获取NeuralProphet生成的原生Plotly预测图
fig1 = m.plot(forecast)
# 追加实际开盘价轨迹
fig1.add_trace(go.Scatter(
    x=data['Date'], 
    y=data['Open'], 
    name='Actual Open Price',
    line=dict(width=2)
))
# 追加实际收盘价轨迹
fig1.add_trace(go.Scatter(
    x=data['Date'], 
    y=data['Close'], 
    name='Actual Close Price',
    line=dict(width=2)
))
# 统一配置图表属性
fig1.layout.update(
    title_text="Actual Stock Price & NeuralProphet Forecast",
    xaxis_rangeslider_visible=True,
    xaxis_title="Date",
    yaxis_title="Price (USD)"
)
# 单次渲染叠加完成的图表
st.plotly_chart(fig1, use_container_width=True)

st.write("Forecast Components")
fig2 = m.plot_components(forecast)
st.write(fig2)

关键修改点

  • 删除原代码中单独渲染原始行情图的plot_raw_data()逻辑,避免生成独立图表
  • 不单独新建Plotly画布,直接在NeuralProphet返回的预测图对象上通过add_trace()追加实际价格折线,保留预测自带的趋势线、置信区间阴影
  • 为不同数据轨迹设置独立名称,自动生成图例区分实际值、预测值
  • 替换已弃用的@st.cache装饰器为@st.cache_data,适配新版Streamlit,避免运行警告

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 01:42:17