简体   繁体   中英

Update Plotly Dash graph on page refresh

New to Plotly Dash. I'm working through the tutorial on my simple example. Learning how to update a graph when new data is added to the data frame (two data frames in this case) and how to connect this with the dropdown that I have on my dashboard.

I want my graphs to get updated with new data on each page load or page refresh (as I will have only a few updates per day.) This is the code I'm working on:

import pandas as pd
import plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

data = [['Blue', 20], ['Red ', 12], ['Green', 33]]
df = pd.DataFrame(data, columns=['Color', 'Number'])
data1 = [['A', 10, 88], ['B ', 50, 45], ['C', 25, 120]]
df1 = pd.DataFrame(data1, columns=['Letter', 'Column1', 'Column2'])

fig = px.bar(df, x=df['Color'], y=df['Number'])
fig1 = px.line(x=df1['Letter'], y=df1['Column1'], color=px.Constant('Column1'),
                     labels=dict(x='Letter', y='Column1', color='Letter'))
fig1.add_bar(x=df1['Letter'], y=df1['Column2'], name='Letter')

app.layout = html.Div(children=[
    html.H1(children='Colors and Letters', style={'text-align': 'center'}),
    html.Div(children='Color', style={'text-align': 'center'}),

    html.Div([
        html.Label(['Choose a graph:'], style={'font-weight': 'bold'}),
        dcc.Dropdown(
            id='dropdown',
            options=[
                {'label': 'Colors', 'value': 'graph1'},
                {'label': 'Letters', 'value': 'graph2'},
            ],
            value='graph1',
            style={"width": "60%"}),

        html.Div(dcc.Graph(id='graph')),
    ]),

])


@app.callback(
    Output('graph', 'figure'),
    [Input(component_id='dropdown', component_property='value')]
)
def select_graph(value):
    if value == 'graph1':
        return fig
    else:
        return fig1


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

Any help would be greatly appreciated. Thanks in advance.

As documented in the section on live update , you should be able to achieve the desired behaviour by defining a function that creates the layout,

def layout():
   return html.Div(...)

and assigning this function as the app layout,

app.layout = layout # note no (), you must assign the function itself, not the layout 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM