Give Legend to a Bar plot

I have a multindex graph and i want to give it legend based on the color i.e., ‘experiece_level’ array
work_year is level

fig = go.Figure()
fig.add_trace(go.Bar(x=s_by_year_exp.index.get_level_values('work_year'),y=s_by_year_exp['salary_in_usd'],text=s_by_year_exp.index.get_level_values('experience_level').map(exp_dict),marker=dict(color=['green','yellow','blue','red']*4),showlegend=True))
fig.update_layout(barmode="stack")
fig.show()

if i plot this i get this

i want the legend be like color box - experience level

I know one can run a loop but i want to know where it is possible to just make it in one line itself
Thankyou in Advance for Answer

Hi @H4CK3R I don’t think that’s possible because the legend is always related to your traces. Since you only have one, there is no way to show what you want to show out of the box.

If you are open to use plotly.express you might generate the same figure in one line using the color parameter.

2 Likes

Yes i am using px.bar but i just wanted to know if there was a way. Thanks for clarifying. I usually plot with graph_objects for scatter and lines and i am exploring diverse plots rn. :smile: