I want to draw a graph when I press the python dash button. So I created a button called btn-run and a callback function called btn_run_click. However, a new plot is not drawn when the button is pressed. The code is attached below. Is there someone who can help?
import dash
from dash import Dash, dcc, html, Input, Output
import plotly.express as px
import pandas as pd
app = dash.Dash(__name__)
app.layout = html.Div([
html.Br(),
html.Button('start', id='btn-run', n_clicks=0,
style={'width':'150px','height':'30px'}),
dcc.Graph(id='main-plot', figure={}),
html.Br()
])
@app.callback(
Output('main-plot', 'children'),
Input('btn-run','n_clicks')
)
def btn_run_click(btn_run):
if btn_run == 0 : return
df = pd.DataFrame({
"Fruits":['Apples', 'Oranges', 'Bananas'],
"Amount":[4,3,6]
})
fig = px.bar(df, x = "Fruits", y = "Amount", barmode='group')
return dcc.Graph(figure=fig)
if __name__ == '__main__':
app.run_server(debug=False, port=8052)
i made some minor changes to your code
import dash
from dash import Dash, dcc, html, Input, Output
import plotly.express as px
import pandas as pd
app = dash.Dash(__name__)
app.layout = html.Div([
html.Br(),
html.Button('start', id='btn-run', n_clicks=0,
style={'width': '150px', 'height': '30px'}),
dcc.Graph(id='main-plot', figure={}),
html.Br()
])
@app.callback(
# change output to main-plot.figure
Output('main-plot', 'figure'),
Input('btn-run', 'n_clicks')
)
def btn_run_click(btn_run):
#if btn_run == 0: return
df = pd.DataFrame({
"Fruits": ['Apples', 'Oranges', 'Bananas'],
"Amount": [4, 3+btn_run, 6]
})
fig = px.bar(df, x="Fruits", y="Amount", barmode='group')
# just return the figure
return fig
if __name__ == '__main__':
app.run_server(debug=False, port=8052)