I am building a dashboard with Plotly Dash. I have used the slider as input for the bar chart. I would like to use the dropdown to highlight a single country in the bar chart. The connection is shown by the yellow arrows in the picture.
I have used the 'fig1.for_each_trace' to connect it to the dropdown. It does not give an error, but does not what I want.
Can anyone help me out?
This link has put me in this direction: https://plotly.com/python/creating-and-updating-figures/#conditionally-updating-traces
The callback I have so far:
'''
@app.callback(
[
Output('barchart-1', 'figure'),
Output('year-1', 'children')
],
Input('year-slider', 'value'),
Input('dropdown-country', 'value')
)
def update_visual(slctd_year, slctd_cntry):
life = df1[df1['Year'] == slctd_year]
country = df1[df1['Entity'] == slctd_cntry]
fig1 = px.bar(
life,
x=life['Entity'],
y=life['Life expectancy'],
# template='simple white'
)
fig1.update_traces(marker_color='rgb(33, 60, 99)',
)
fig1.update_layout(
height= 315,
margin=dict(l=20, r=30, t=50, b=30),
plot_bgcolor='rgb(0,0,0,0)',
legend_bgcolor='rgba(0,0,0,0)',
paper_bgcolor='rgb(0,0,0,0)',
font_color='#909090'
)
fig1.for_each_trace(
lambda trace: trace.update(marker_color='#9D3469') if trace == country else (),
)
return fig1, 'Year: {0}'.format(slctd_year)
'''
On the Plotly community forum I got this answer and it works perfectly fine!
'''
fig1["data"][0]["marker"]["color"] = ["red" if c == slctd_cntry else "blue" for c in fig1["data"][0]["x"]]
'''
This is the link to the topic: https://community.plotly.com/t/how-to-highlight-a-single-bar-on-select-in-plotly-dash/60739/2
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.