Plotly:单击按钮后如何显示图形? [英] Plotly: How to display graph after clicking a button?

查看:75
本文介绍了Plotly:单击按钮后如何显示图形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想仅在单击按钮后才使用 plotly 来显示图形,但我不确定如何进行此操作.我的图存储在下面的代码位

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

然后我使用以下代码位定义我的应用布局:

app.layout = html.Div([#按钮html.Div(className='submit', children=[html.Button('预测', id='submit', n_clicks=0)]),#加载dcc.Loading(id="loading-1",类型=默认",children=html.Div(id=loading-output-1")),#图形dcc.Graph(id='mpg-scatter',figure=fig),#hoverdatahtml.div([dcc.Markdown(id='hoverdata-text')],style={'width':'50%','display':'inline-block'})])@app.callback(Output('hoverdata-text','children'),[输入('mpg-scatter','hoverData')])def callback_stats(hoverData):返回 str(hoverData)如果 __name__ == '__main__':app.run_server()

但问题是我只想先显示按钮.然后当有人点击预测按钮时,加载功能出现,一秒钟后图表显示.我定义了一个 dcc.loading 组件,但不确定如何定义此功能的回调.

解决方案


建议 3 - dcc.Store()dcc.Loading

这个建议使用了一个

现在你可以点击Figures一次得到下面的Figure 1,但只有在享受以下加载图标之一后:['graph', 'cube', 'circle', 'dot', or 'default'] 其中 'dot' 将触发 ptsd,而 'cube' 恰好是我的最喜欢:

正在加载...

图 1

现在您可以继续点击Figure 2Figure 3.我将Figure 1的加载时间设置为不少于5秒,然后Figure 2Figure 3的加载时间为2秒.但您可以轻松更改它.

如果您点击了 3 次以上,我们将重新从头开始:

我希望我终于找到了您真正需要的解决方案.下面代码片段中的设置建立在

现在您可以自由选择要显示的图形,也可以返回不显示任何内容,如下所示:

启动时显示,或选择None时:

图1被选中

您仍未提供数据样本,因此我仍在使用来自建议 1 的合成数据,而是让不同的布局指示显示的是哪个图.我希望这能满足您的需求,因为您似乎希望为不同的图形使用不同的布局.

完成代码2

from jupyter_dash import JupyterDash将 dash_core_components 导入为 dcc将 dash_html_components 导入为 html从 dash.dependencies 导入输入、输出、状态、ClientsideFunction将 dash_bootstrap_components 导入为 dbc将 dash_bootstrap_components 导入为 dbc将 dash_core_components 导入为 dcc将 dash_html_components 导入为 html将熊猫导入为 pd导入 plotly.graph_objs as go从 dash.dependencies 导入输入,输出将 numpy 导入为 np从 plotly.subplots 导入 make_subplots导入 plotly.express 作为 pxpd.options.plotting.backend = "plotly";从日期时间导入日期时间调色板 = px.colors.qualitative.Plotly# 样本数据df = pd.DataFrame({'价格': [1,10,7,5, np.nan, np.nan, np.nan],'Predicted_prices':[np.nan, np.nan, np.nan, 5, 8,6,9]})# 应用设置app = JupyterDash(external_stylesheets=[dbc.themes.SLATE])# 控件控件 = dbc.Card([dbc.FormGroup([dbc.Label(选项"),dcc.RadioItems(id="display_figure",options=[ {'label': 'None', 'value': 'Nope'},{'label': '图 1', 'value': 'Figure1'},{'label': 'Figure 2', 'value': 'Figure2'},{'label': 'Figure 3', 'value': 'Figure3'}],值='不',labelStyle={'display': 'inline-block', 'width': '10em', 'line-height':'0.5em'})],),dbc.FormGroup([dbc.Label(""),]),],身体=真,样式 = {'字体大小':'大'})app.layout = dbc.Container([html.H1(预测按钮"),html.hr(),dbc.Row([dbc.Col([控件],xs = 4),dbc.Col([dbc.Row([dbc.Col(dcc.Graph(id=预测")),])]),]),html.Br(),dbc.Row([]),],流体=真,)@app.callback(输出(预测",数字"),[输入(display_figure",值"),],)def make_graph(display_figure):# 主要跟踪y = '价格'y2 = '预测价格'# 打印(显示图形)如果 display_figure 中的Nope":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)')))返回无花果如果 display_figure 中的Figure1":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')# 预测轨迹如果 display_figure 中的Figure2":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')如果 display_figure 中的Figure3":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')#美学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 =价格和预测")返回(图)app.run_server(mode='external', port = 8005)


建议 1


此建议将直接关注:

<块引用>

我想使用 plotly 仅在单击按钮后显示图表

这意味着我不认为 dcc.Loading() 必须 成为答案的一部分.


我发现 dcc.Checklist() 是一个非常通用且用户友好的组件.如果设置正确,它将显示为必须单击的按钮(或必须标记的选项)才能触发某些功能或可视化.

这是一个基本设置:

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

这是它的样子:

除其他外,还有以下几行,dcc.Checklist() 组件将让您可以随意打开和关闭 Prediction 跟踪.

# 主要跟踪y = '价格'fig = make_subplots(specs=[[{secondary_y": True}]])如果 display_columns 中的价格":fig.add_trace(go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines'), secondary_y=False)# 预测轨迹如果 display_columns 中的Predicted_prices":fig.add_trace(go.Scatter(name = 'predictions', x=df.index, y=df['Predicted_prices'], mode = 'lines'), secondary_y=False

此外,如果您想进一步扩展此示例,此设置将让您轻松处理 multiple 跟踪的 multiple 预测.试一试,让我知道它对你有用.如果有什么不清楚的,那么我们可以在您找到时间时深入了解细节.

以下是应用在启用和不启用预测的情况下的外观:

关闭

开启

完整代码:

from jupyter_dash import JupyterDash将 dash_core_components 导入为 dcc将 dash_html_components 导入为 html从 dash.dependencies 导入输入、输出、状态、ClientsideFunction将 dash_bootstrap_components 导入为 dbc将 dash_bootstrap_components 导入为 dbc将 dash_core_components 导入为 dcc将 dash_html_components 导入为 html将熊猫导入为 pd导入 plotly.graph_objs as go从 dash.dependencies 导入输入,输出将 numpy 导入为 np从 plotly.subplots 导入 make_subplots导入 plotly.express 作为 pxpd.options.plotting.backend = "plotly";从日期时间导入日期时间调色板 = px.colors.qualitative.Plotly# 样本数据df = pd.DataFrame({'价格': [1,10,7,5, np.nan, np.nan, np.nan],'Predicted_prices':[np.nan, np.nan, np.nan, 5, 8,6,9]})# 应用设置app = JupyterDash(external_stylesheets=[dbc.themes.SLATE])# 输入控件控件 = dbc.Card([dbc.FormGroup([dbc.Label(选项"),dcc.清单(id="display_columns",options=[{"label": col + ' ', "value": col} for col in df.columns],值=[df.columns[0]],labelStyle={'display': 'inline-block', 'width': '12em', 'line-height':'0.5em'}#clearable=假,#multi = 真),],),dbc.FormGroup([dbc.Label(""),]),],身体=真,样式 = {'字体大小':'大'})app.layout = dbc.Container([html.H1(预测按钮"),html.hr(),dbc.Row([dbc.Col([控件],xs = 4),dbc.Col([dbc.Row([dbc.Col(dcc.Graph(id=预测")),])]),]),html.Br(),dbc.Row([]),],流体=真,)@app.callback(输出(预测",数字"),[输入(display_columns",值"),],)def make_graph(display_columns):# 主要跟踪y = '价格'fig = make_subplots(specs=[[{secondary_y": True}]])如果 display_columns 中的价格":fig.add_trace(go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines'), secondary_y=False)# 预测轨迹如果 display_columns 中的Predicted_prices":fig.add_trace(go.Scatter(name = 'predictions', x=df.index, y=df['Predicted_prices'], mode = 'lines'), secondary_y=False)#美学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 =价格和预测")返回(图)app.run_server(mode='external', port = 8005)

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)

这篇关于Plotly:单击按钮后如何显示图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆