简体   繁体   中英

Plotly: How to display graph after clicking a button?

I want to use plotly to display a graph only after a button is clicked but am not sure how to make this work. My figure is stored in the following code bit

    fig1 = go.Figure(data=plot_data, layout=plot_layout)

I then define my app layout with the following code bit:

app.layout = html.Div([
                #button
                html.Div(className='submit', children=[

                html.Button('Forecast', id='submit', n_clicks=0)
                ]),
                #loading 
                dcc.Loading(
                id="loading-1",
                type="default",
                children=html.Div(id="loading-output-1")
                ),
                #graph
                dcc.Graph(id= 'mpg-scatter',figure=fig),
    
                #hoverdata
                html.Div([
                    dcc.Markdown(id='hoverdata-text')
                ],style={'width':'50%','display':'inline-block'})
])

@app.callback(Output('hoverdata-text','children'),
             [Input('mpg-scatter','hoverData')])

def callback_stats(hoverData):
    return str(hoverData)


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

But the problem is i only want the button displayed at first. Then when someone clicks on the forecast button the loading feature appears and a second later the graph displays. I defined a dcc.loading component but am not sure how to define the callback for this feature.


SUGGESTION 3 - dcc.Store() and dcc.Loading

This suggestion uses a dcc.Store() component, a html.Button() and a dcc.Loading component to produce what I now understand to be the desired setup:

  1. Launch an app that only shows a button.
  2. Click a button to show a loading icon, and then
  3. display a figure.
  4. Click again to show the next figure in a sequence of three figures.
  5. Start again when the figure sequence is exhausted.

Upon launch, the app will look like this:

在此处输入图片说明

Now you can click Figures once to get Figure 1 below, but only after enjoying one of the following loading icons: ['graph', 'cube', 'circle', 'dot', or 'default'] of which 'dot' will trigger ptsd, and 'cube' happens to be my favorite:

Loading...

在此处输入图片说明

Figure 1

在此处输入图片说明

Now you cann keep on clicking for Figure 2 and Figure 3 . I've set the loading time for Figure 1 no less than 5 seconds, and then 2 seconds for Figure 2 and Figure 3 . But you can easily change that.

When you've clicked more than three times, we start from the beginning again:

在此处输入图片说明

I hope I've finally figured out a solution for what you were actually looking for. The setup in the code snippet below builds on the setup described here , but has been adjusted to hopefully suit your needs. Let me know how this works out for you!

import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.graph_objects as go
from jupyter_dash import JupyterDash
import dash_table
from dash.exceptions import PreventUpdate
import dash_bootstrap_components as dbc
import time
time.sleep(5) # Delay for 5 seconds.

global_df = pd.DataFrame({'value1':[1,2,3,4],
                          'value2':[10,11,12,14]})

# app = JupyterDash(__name__)
app = JupyterDash(external_stylesheets=[dbc.themes.SLATE])

df = pd.DataFrame({'Value 1': [1,2,3],
                   'Value 2':[10,11,12],
                   'Value 3':[14,12,9]})

df.set_index('Value 1', inplace = True)

app.layout = html.Div([
    # The memory store reverts to the default on every page refresh
    dcc.Store(id='memory'),
    # The local store will take the initial data
    # only the first time the page is loaded
    # and keep it until it is cleared.
    # Same as the local store but will lose the data
    # when the browser/tab closes.
    html.Table([
        html.Thead([
            html.Tr(html.Th('Click to launch figure:')),
            html.Tr([
                html.Th(html.Button('Figures', id='memory-button')),
            ]),
        ]),
    ]),    
     dcc.Loading(id = "loading-icon",
                  #'graph', 'cube', 'circle', 'dot', or 'default'
                 type = 'cube',
                children=[html.Div(dcc.Graph(id='click_graph'))])
])

# Create two callbacks for every store.
# add a click to the appropriate store.
@app.callback(Output('memory', 'data'),
              [Input('memory-button', 'n_clicks')],
              [State('memory', 'data')])
def on_click(n_clicks, data):
    if n_clicks is None:
        # prevent the None callbacks is important with the store component.
        # you don't want to update the store for nothing.
        raise PreventUpdate

    # Give a default data dict with 0 clicks if there's no data.
    data = data or {'clicks': 0}
    data['clicks'] = data['clicks'] + 1
    if data['clicks'] > 3: data['clicks'] = 0
    
    return data

# output the stored clicks in the table cell.
@app.callback(Output('click_graph', 'figure'),
              # Since we use the data prop in an output,
              # we cannot get the initial data on load with the data prop.
              # To counter this, you can use the modified_timestamp
              # as Input and the data as State.
              # This limitation is due to the initial None callbacks
              # https://github.com/plotly/dash-renderer/pull/81
              [Input('memory', 'modified_timestamp')],
              [State('memory', 'data')])
def on_data(ts, data):
    if ts is None:
         #raise PreventUpdate
        fig = go.Figure()
        fig.update_layout(plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)',
                          yaxis = dict(showgrid=False, zeroline=False, tickfont = dict(color = 'rgba(0,0,0,0)')),
                          xaxis = dict(showgrid=False, zeroline=False, tickfont = dict(color = 'rgba(0,0,0,0)')))
        return(fig)
    data = data or {}
    0
    # plotly
    y = 'Value 2'
    y2 = 'Value 3'
    
    fig = go.Figure()
    fig.update_layout(plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)',
                          yaxis = dict(showgrid=False, zeroline=False, tickfont = dict(color = 'rgba(0,0,0,0)')),
                          xaxis = dict(showgrid=False, zeroline=False, tickfont = dict(color = 'rgba(0,0,0,0)')))
    
    if data.get('clicks', 0) == 1:
        fig = go.Figure(go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines'))
        fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode = 'lines'))
        fig.update_layout(template='plotly_dark',
                          title = 'Plot number ' + str(data.get('clicks', 0)))
    
        # delay only after first click
        time.sleep(2)
    
    if data.get('clicks', 0) == 2:
        fig = go.Figure((go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines')))
        fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode = 'lines'))
        fig.update_layout(template='seaborn',
                          title = 'Plot number ' + str(data.get('clicks', 0)))
        
    if data.get('clicks', 0) == 3:
        fig = go.Figure((go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines')))
        fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode = 'lines'))
        fig.update_layout(template='plotly_white',
                          title = 'Plot number ' + str(data.get('clicks', 0)))

    # Aesthetics
    fig.update_layout(margin= {'t':30, 'b':0, 'r': 50, 'l': 50, 'pad': 0},
                      hovermode = 'x',
                      legend=dict(x=1,y=0.85),
                      uirevision='constant')
    
    # delay for every figure
    time.sleep(2)
    return fig

app.run_server(mode='external', port = 8070, dev_tools_ui=True,
          dev_tools_hot_reload =True, threaded=True)

SUGGESTION 2


After a little communation we now know that you'd like to:

  • only display a button first (question)
  • when the button is clicked once fig 1 is displayed at the bottom , on 2nd click fig 2 is displayed, and on 3rd click fig 3 is displayed (comment)

I've made a new setup that should meet all criteria above. At first, only the control options are being showed. And then you can select which figure to display: Fig1, Fig2 or Fig3 . To me it would seem like a non-optimal user iterface if you have to cycle through your figures in order to select which one you would like to display. So I'v opted for radio buttons such as this:

在此处输入图片说明

Now you can freely select your figure to display, or go back to showing nothing again, like this:

Display on startup, or when None is selected:

在此处输入图片说明

Figure 1 is selected

在此处输入图片说明

You still haven't provided a data sample, so I'm still using my synthetic data from Suggestion 1 , and rather letting the different layouts indicate which figure is shown. I hope that suits your needs since it seemed that you would like to have different layouts for the different figures.

Complete code 2

from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, ClientsideFunction
import dash_bootstrap_components as dbc
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
import numpy as np
from plotly.subplots import make_subplots
import plotly.express as px
pd.options.plotting.backend = "plotly"
from datetime import datetime

palette = px.colors.qualitative.Plotly

# sample data
df = pd.DataFrame({'Prices': [1,10,7,5, np.nan, np.nan, np.nan],
                    'Predicted_prices':[np.nan, np.nan, np.nan, 5, 8,6,9]})

# app setup
app = JupyterDash(external_stylesheets=[dbc.themes.SLATE])

# controls
controls = dbc.Card(
      [dbc.FormGroup(
            [
                dbc.Label("Options"),
                                dcc.RadioItems(id="display_figure", 
                                options=[   {'label': 'None', 'value': 'Nope'},
                                            {'label': 'Figure 1', 'value': 'Figure1'},
                                            {'label': 'Figure 2', 'value': 'Figure2'},
                                            {'label': 'Figure 3', 'value': 'Figure3'}
                                ],
                                value='Nope',
                                labelStyle={'display': 'inline-block', 'width': '10em', 'line-height':'0.5em'}
                                ) 
            ], 
        ),
        dbc.FormGroup(
            [dbc.Label(""),]
        ),
    ],
    body=True,
    style = {'font-size': 'large'})

app.layout = dbc.Container(
    [
        html.H1("Button for predictions"),
        html.Hr(),
        dbc.Row([
            dbc.Col([controls],xs = 4),
            dbc.Col([
                dbc.Row([
                    dbc.Col(dcc.Graph(id="predictions")),
                ])
            ]),
        ]),
        html.Br(),
        dbc.Row([
 
        ]), 
    ],
    fluid=True,
)

@app.callback(
    Output("predictions", "figure"),
    [Input("display_figure", "value"),

    ],
)
def make_graph(display_figure):

    # main trace
    y = 'Prices'
    y2 = 'Predicted_prices'
#     print(display_figure)
    if 'Nope' in display_figure:
        fig = go.Figure()
        fig.update_layout(plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)',
                          yaxis = dict(showgrid=False, zeroline=False, tickfont = dict(color = 'rgba(0,0,0,0)')),
                          xaxis = dict(showgrid=False, zeroline=False, tickfont = dict(color = 'rgba(0,0,0,0)')))
        return fig

    if 'Figure1' in display_figure:
        fig = go.Figure(go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines'))
        fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode = 'lines'))
        fig.update_layout(template='plotly_dark')

    # prediction trace
    if 'Figure2' in display_figure:
        fig = go.Figure((go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines')))
        fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode = 'lines'))
        fig.update_layout(template='seaborn')

    if 'Figure3' in display_figure:
        fig = go.Figure((go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines')))
        fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode = 'lines'))
        fig.update_layout(template='plotly_white')

    # Aesthetics
    fig.update_layout(margin= {'t':30, 'b':0, 'r': 0, 'l': 0, 'pad': 0})
    fig.update_layout(hovermode = 'x')
    fig.update_layout(showlegend=True, legend=dict(x=1,y=0.85))
    fig.update_layout(uirevision='constant')
    fig.update_layout(title = "Prices and predictions")

    return(fig)

app.run_server(mode='external', port = 8005)

SUGGESTION 1


This suggestion will focus directly on:

I want to use plotly to display a graph only after a button is clicked

Which means that I don't assume that dcc.Loading() has to be a part of the answer.


I find that dcc.Checklist() is an extremely versatile and user-friendly component. And when set up correctly, it will appear as a button that has to be clicked (or an option that has to be marked) in order to trigger certain functionalities or visualizations.

Here's a basic setup:

dcc.Checklist(
    id="display_columns",                    
    options=[{"label": col + ' ', "value": col} for col in df.columns],
    value=[df.columns[0]],
    labelStyle={'display': 'inline-block', 'width': '12em', 'line-height':'0.5em'}

And here's how it will look like:

在此处输入图片说明

Along with, among other things, the following few lines, the dcc.Checklist() component will let you turn the Prediction trace on and off as you please.

# main trace
y = 'Prices'
fig = make_subplots(specs=[[{"secondary_y": True}]])
if 'Prices' in display_columns:
    fig.add_trace(go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines'), secondary_y=False)

# prediction trace
if 'Predicted_prices' in display_columns:
    fig.add_trace(go.Scatter(name = 'predictions', x=df.index, y=df['Predicted_prices'], mode = 'lines'), secondary_y=False

Adding to that, this setup will easily let you handle multiple predictions for multiple traces if you would like to extend this example further. Give it a try, and let me know how it works out for you. And if something is not clear, then we can dive into the details when you find the time.

Here's how the app will look like with and without Predictions activated:

OFF

在此处输入图片说明

ON

在此处输入图片说明

Complete code:

from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, ClientsideFunction
import dash_bootstrap_components as dbc
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
import numpy as np
from plotly.subplots import make_subplots
import plotly.express as px
pd.options.plotting.backend = "plotly"
from datetime import datetime

palette = px.colors.qualitative.Plotly

# sample data
df = pd.DataFrame({'Prices': [1,10,7,5, np.nan, np.nan, np.nan],
                    'Predicted_prices':[np.nan, np.nan, np.nan, 5, 8,6,9]})

# app setup
app = JupyterDash(external_stylesheets=[dbc.themes.SLATE])

# input controls
controls = dbc.Card(
      [dbc.FormGroup(
            [
                dbc.Label("Options"),
                                dcc.Checklist(
                                    id="display_columns",                    
                                    options=[{"label": col + ' ', "value": col} for col in df.columns],
                                    value=[df.columns[0]],
                                    labelStyle={'display': 'inline-block', 'width': '12em', 'line-height':'0.5em'}
                    #clearable=False,
                    #multi = True
                ),
            ], 
        ),

        dbc.FormGroup(
            [dbc.Label(""),]
        ),
    ],
    body=True,
    style = {'font-size': 'large'})

app.layout = dbc.Container(
    [
        html.H1("Button for predictions"),
        html.Hr(),
        dbc.Row([
            dbc.Col([controls],xs = 4),
            dbc.Col([
                dbc.Row([
                    dbc.Col(dcc.Graph(id="predictions")),
                ])
            ]),
        ]),
        html.Br(),
        dbc.Row([
 
        ]), 
    ],
    fluid=True,
)

@app.callback(
    Output("predictions", "figure"),
    [Input("display_columns", "value"),

    ],
)
def make_graph(display_columns):

    # main trace
    y = 'Prices'
    fig = make_subplots(specs=[[{"secondary_y": True}]])
    if 'Prices' in display_columns:
        fig.add_trace(go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines'), secondary_y=False)
    
    # prediction trace
    if 'Predicted_prices' in display_columns:
        fig.add_trace(go.Scatter(name = 'predictions', x=df.index, y=df['Predicted_prices'], mode = 'lines'), secondary_y=False)
    
    # Aesthetics
    fig.update_layout(margin= {'t':30, 'b':0, 'r': 0, 'l': 0, 'pad': 0})
    fig.update_layout(hovermode = 'x')
    fig.update_layout(showlegend=True, legend=dict(x=1,y=0.85))
    fig.update_layout(uirevision='constant')
    fig.update_layout(template='plotly_dark',
                      plot_bgcolor='#272B30', 
                      paper_bgcolor='#272B30')
    fig.update_layout(title = "Prices and predictions")
    return(fig)

app.run_server(mode='external', port = 8005)

I am looking for a very similar solution and I tried your suggestion 2. Because I want to display images depending upon user's choice of clicking button. I have image_1, image_2, image_3 and image_4 under one directory. I want to update form your solution and display the images. I have tried so far like below. But couldn't proceed due to error as this is my first try with plotly and dash and a beginner. Thanks.

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
import numpy as np
from plotly.subplots import make_subplots
import plotly.express as px

pd.options.plotting.backend = "plotly"
from datetime import datetime

palette = px.colors.qualitative.Plotly

# sample data
df = pd.DataFrame({'Prices': [1, 10, 7, 5, np.nan, np.nan, np.nan],
                   'Predicted_prices': [np.nan, np.nan, np.nan, 5, 8, 6, 9]})

# app setup
app = dash.Dash()

# controls
controls = dcc.Card(
    [dcc.FormGroup(
        [
            dcc.Label("Options"),
            dcc.RadioItems(id="display_figure",
                           options=[{'label': 'None', 'value': 'Nope'},
                                    {'label': 'Figure 1', 'value': 'Figure1'},
                                    {'label': 'Figure 2', 'value': 'Figure2'},
                                    {'label': 'Figure 3', 'value': 'Figure3'}
                                    ],
                           value='Nope',
                           labelStyle={'display': 'inline-block', 'width': '10em', 'line-height': '0.5em'}
                           )
        ],
    ),
        dcc.FormGroup(
            [dcc.Label(""), ]
        ),
    ],
    body=True,
    style={'font-size': 'large'})

app.layout = dcc.Container(
    [
        html.H1("Button for predictions"),
        html.Hr(),
        dcc.Row([
            dcc.Col([controls], xs=4),
            dcc.Col([
                dcc.Row([
                    dcc.Col(dcc.Graph(id="predictions")),
                ])
            ]),
        ]),
        html.Br(),
        dcc.Row([

        ]),
    ],
    fluid=True,
)


@app.callback(
    Output("predictions", "figure"),
    [Input("display_figure", "value"),

     ],
)
def make_graph(display_figure):
    # main trace
    y = 'Prices'
    y2 = 'Predicted_prices'
    #     print(display_figure)
    if 'Nope' in display_figure:
        fig = go.Figure()
        fig.update_layout(plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)',
                          yaxis=dict(showgrid=False, zeroline=False, tickfont=dict(color='rgba(0,0,0,0)')),
                          xaxis=dict(showgrid=False, zeroline=False, tickfont=dict(color='rgba(0,0,0,0)')))
        return fig

    if 'Figure1' in display_figure:
        fig = go.Figure(go.Scatter(name=y, x=df.index, y=df[y], mode='lines'))
        fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode='lines'))
        fig.update_layout(template='plotly_dark')

    # prediction trace
    if 'Figure2' in display_figure:
        fig = go.Figure((go.Scatter(name=y, x=df.index, y=df[y], mode='lines')))
        fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode='lines'))
        fig.update_layout(template='seaborn')

    if 'Figure3' in display_figure:
        fig = go.Figure((go.Scatter(name=y, x=df.index, y=df[y], mode='lines')))
        fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode='lines'))
        fig.update_layout(template='plotly_white')

    # Aesthetics
    fig.update_layout(margin={'t': 30, 'b': 0, 'r': 0, 'l': 0, 'pad': 0})
    fig.update_layout(hovermode='x')
    fig.update_layout(showlegend=True, legend=dict(x=1, y=0.85))
    fig.update_layout(uirevision='constant')
    fig.update_layout(title="Prices and predictions")

    return (fig)


app.run_server(debug=True)

Error as below: line 24, in controls = dcc.Card( AttributeError: module 'dash_core_components' has no attribute 'Card'

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