Plotly Express: Legend inside figure

Hey,

I wonder if it is possible to bring the legend inside a figure. I have a callback where a figure is created and send via callback to a dcc.Graph. I tried figure.update(layout…legnd:{}). But the legend is still outside.

Best regards!

It’s definitely possible to move the legend wherever you’d like with .update(). Can you share a more complete example of the code that’s not working for you?

Hi @nicolaskruchten,

Adding to this scenario…
Plotly express scatter_mapbox legends are placed on the top right hand corner by default. Is there a way to move them to the bottom or elsewhere ?

Thanks
Ananth

Just in case someone encounters this problem and needs more explanation, this is how I did it with (a dummy example).

Start with creating your plot, assign the output to a variable

data = px.data.tips()
p = px.scatter(data,x=‘total_bill’,y=‘tip’,color=‘sex’)

then, you can call the update function for the layout on the variable p. For instance, setting a horizontal legend below the figure:

p.update_layout({‘legend_orientation’:‘h’})

All regular plotly layout arguments work, but pass them formatted as a dict, and keep to the plotly API specification. For instance, setting figure margins and the legend:

p.update_layout({‘margin’:{‘t’:25,‘l’:50},‘legend_orientation’:‘h’}

Hope this helps, it took me a while to figure this out.
Bernie.

2 Likes

bcaessens’s solution didn’t work for me but this did:

fig = px.scatter_3d(df)
fig.update_layout(legend_orientation=‘h’)

I hope this is helpful for someone!