The callback needs to return a figure object (created by go.Figure
or by a plotly express function), so you don’t need to call fig.show()
(the Dash server takes care of the rendering). For generating the figure, you can either replace go.Bar
by go.Histogram
in your snippet, or call px.histogram
to generate directly the figure.
Solution 1
@app.callback(Output("city-bar", "figure"),
[Input("state-bar", "hoverData")])
def on_hover(hover_data):
if not hover_data:
return dash.no_update
state = hover_data["points"][0]["x"]
sales = df.loc[df.state == state]
return go.Figure(
[go.Histogram(
x=sales.city,
y=sales.sales,
width=.2,
histfunc='sum',
name="City"
)],
layout=go.Layout(
xaxis={'title': 'City'},
yaxis={'title': 'Sales'},
margin=dict(
b=50, #bottom margin 40px
l=50, #left margin 40px
r=50, #right margin 20px
t=50, #top margin 20px
),
bargap=.1
))
Solution 2
@app.callback(Output("city-bar", "figure"),
[Input("state-bar", "hoverData")])
def on_hover(hover_data):
if not hover_data:
return dash.no_update
state = hover_data["points"][0]["x"]
sales = df.loc[df.state == state]
fig = px.histogram(sales,
x='city',
y='sales',
histfunc='sum',
title='City')
fig.update_layout(
dict(
xaxis={'title': 'City'},
yaxis={'title': 'Sales'},
margin=dict(
b=50, #bottom margin 40px
l=50, #left margin 40px
r=50, #right margin 20px
t=50, #top margin 20px
),
bargap=.1
))
return fig
(I did not execute this code since I did not have your data, I hope there is no typo)
For a future question, don’t hesitate to post from the start a minimal example of code, it will help us giving a relevant answer.