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

Plotly Dash下拉选择月份后Heatmap热力图不更新问题求解

问题原因分析
  • 核心错误1:回调函数返回值类型不匹配。dcc.Graph的figure属性需要接收包含data和layout两个字段的完整图表对象,你当前代码直接返回了go.Heatmap traces对象,不符合参数要求,因此图表无法刷新。
  • 核心错误2:go.Heatmap类本身不支持title参数,标题配置需要放到图表的layout属性中。
主要改动说明
  • 回调函数内使用go.Figure()封装Heatmap实例,返回完整的figure对象,符合dcc.Graph的参数要求
  • 将标题、坐标轴配置统一放到update_layout方法中设置,符合Plotly的参数规范
  • 删除了初始dcc.Graph里冗余的静态figure配置,回调会自动生成初始图表,避免重复代码
修复后可运行代码

首先确保你已经导入了必要依赖:

import dash
from dash import html, dcc, Input, Output
import plotly.graph_objects as go
import pandas as pd
# 你的New数据框定义在该位置

完整业务代码:

Month_Default = New['Month'].unique()
Month_def = 2
# 创建dash应用
app = dash.Dash()

app.layout = html.Div([
    html.H1('//Title'),
    html.Div([
        html.Div([
            html.H4('选择月份...'),
            dcc.Dropdown(
                id='Month_dropdown',
                options=[{'label': i, 'value': i} for i in Month_Default],
                value = Month_def
            ),
        ],
        style={'width': '48%', 'display': 'inline-block'}),
        dcc.Graph(id='heatmap')
    ])
])

@app.callback(
    Output(component_id='heatmap',component_property='figure'),
    Input(component_id='Month_dropdown',component_property='value')
)
def update_graph(selected_month):
    filtered_df = New[New['Month'] == selected_month]
    # 构建完整的figure对象
    fig = go.Figure(data=go.Heatmap(
        x=filtered_df['Days'],
        y=filtered_df['Hour'],
        z=filtered_df['Usage'],
        colorscale='Viridis'
    ))
    # 配置布局参数
    fig.update_layout(
        title='PM KWH使用量',
        xaxis_title = '日期',
        yaxis_title = '小时'
    )
    return fig

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:45:03