首页 > 解决方案 > 根据“Dash”中的用户选择创建图表

问题描述

我对 python 和“Dash”非常陌生——我正在寻找一种方法,可以从选择的数据中绘制图表。

以下是我的代码,但由于某种原因,我在选择一个选项后只返回一个空白图?

我认为问题出现在“Def 交互式图表”部分。

import dash
import dash_core_components as dcc
import dash_html_components as html
import time
from collections import deque
import plotly.graph_objs as go
import random
import plotly.express as px
import pandas as pd


df = pd.read_csv("d5.csv").tail(10) 

from dash.dependencies import Output, Input

app = dash.Dash(__name__)


app.layout=html.Div([
    html.H1("Graph Analysis"),

    dcc.Dropdown(id='graph-choice',
                 options=[{'label':'Room 1 Temperature', 'value':'R1Temp'},
                          {'label':'Room 2 Temperature', 'value':'R2Temp'},
                          {'label':'Room 3 Temperature', 'value':'R3Temp'}],
                          
                 value='R1Temp'
                 ),
    dcc.Graph(id='my-graph', figure={}
              )
])


@app.callback(
    Output(component_id='my-graph', component_property='figure'),
    Input(component_id='graph-choice', component_property='value')
)

def interactive_graphs(selected_value):
    
    if selected_value == 'R1Temp':
        fig_line = px.line(data_frame=df, x='Time', y='R1Temp')

    else if selected_value == 'R2Temp':
        fig_line = px.line(data_frame=df, x='Time', y='R1Temp')


    else:
        fig_line = px.line(data_frame=df, x='Time', y='R3Temp')
        


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

标签: pythongraphplotlyplotly-dashinteractive

解决方案


您没有在回调中返回任何内容。你应该返回这个数字,即你的回调应该是这样的,

@app.callback(Output('my-graph', 'figure'), Input('graph-choice', 'value'))
def interactive_graphs(selected_value):
    if selected_value == 'R1Temp':
        return px.line(data_frame=df, x='Time', y='R1Temp')
    if selected_value == 'R2Temp':
        return px.line(data_frame=df, x='Time', y='R1Temp')
    return px.line(data_frame=df, x='Time', y='R3Temp')

推荐阅读