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

Dash多子图调整需求:将Price与MMA30合并至同一子图

解决方案:将Price与MMA30合并到同一Dash子图

没问题!要实现把Price和MMA30折线合并到同一个子图中,我们只需要调整子图的布局结构,把这两个数据系列放在同一个坐标轴上展示。下面是修改后的完整可复现代码,关键改动我都加了注释:

import dash
import requests
import pandas as pd
from dash.dependencies import Output, Input
import dash_core_components as dcc
import dash_html_components as html
import plotly.tools as tls
import plotly.graph_objects as go
from io import StringIO

app = dash.Dash(__name__)

# 模拟获取数据逻辑(可替换为你的真实数据源)
def get_stock_data():
    csv_sample = """Date,Price,MMA30,Volume
2024-01-01,100,98,10000
2024-01-02,102,99,12000
2024-01-03,101,100,9000
2024-01-04,105,101,15000
2024-01-05,104,102,11000
2024-01-06,106,103,13000
"""
    df = pd.read_csv(StringIO(csv_sample))
    df['Date'] = pd.to_datetime(df['Date'])
    return df

# 初始化2行子图:第一行放Price+MMA30,第二行放Volume
initial_fig = tls.make_subplots(rows=2, cols=1, shared_xaxes=True, 
                                vertical_spacing=0.1,
                                subplot_titles=("Price & MMA30", "Volume"))

app.layout = html.Div([
    dcc.Graph(id='stock-analysis-graph', figure=initial_fig),
    # 可添加其他交互组件(如日期选择器、股票代码下拉框)
])

@app.callback(
    Output('stock-analysis-graph', 'figure'),
    Input('stock-analysis-graph', 'id')  # 替换为你的实际输入组件,如下拉框value
)
def update_graph(_):
    df = get_stock_data()
    # 保持子图结构与初始化一致
    fig = tls.make_subplots(rows=2, cols=1, shared_xaxes=True, 
                            vertical_spacing=0.1,
                            subplot_titles=("Price & MMA30", "Volume"))
    
    # 给第一行子图添加Price折线
    fig.add_trace(
        go.Scatter(x=df['Date'], y=df['Price'], name='Price', line=dict(color='#1f77b4')),
        row=1, col=1
    )
    
    # 给第一行子图添加MMA30折线(用虚线区分)
    fig.add_trace(
        go.Scatter(x=df['Date'], y=df['MMA30'], name='MMA30', line=dict(color='#ff7f0e', dash='dash')),
        row=1, col=1
    )
    
    # 第二行子图保留Volume柱状图
    fig.add_trace(
        go.Bar(x=df['Date'], y=df['Volume'], name='Volume', marker_color='#949494'),
        row=2, col=1
    )
    
    # 优化整体布局与坐标轴样式
    fig.update_layout(height=650, title_text='Stock Price & Volume Analysis', showlegend=True)
    fig.update_xaxes(title_text='Date', row=2, col=1)
    fig.update_yaxes(title_text='Price', row=1, col=1)
    fig.update_yaxes(title_text='Volume', row=2, col=1)
    
    return fig

if __name__ == '__main__':
    app.run_server(debug=True)

核心改动说明:

  • 子图结构调整:把原来的3行子图改为2行,第一行专门承载Price和MMA30,第二行保留Volume,同时开启shared_xaxes=True让两个子图共享X轴,交互时同步缩放、平移,提升体验。
  • 合并数据系列:在回调中给第一行子图连续添加两条Scatter轨迹,这样两个折线就会在同一个坐标轴上展示,方便直观对比走势。
  • 视觉区分优化:给MMA30设置了橙色虚线样式,和Price的蓝色实线形成明显区别,避免混淆。

这样修改后,既能在同一子图里清晰对比价格和均线的关联,又能保留成交量的独立展示,完美满足你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:19:14