Plotly: How to change background color of a plotly express legend?
Asked Answered
G

2

6

The commented out line is my best guess.

    def _make_json(self, given_panda: pd.DataFrame, sort_by: str) -> str:
        figure = px.scatter_mapbox(given_panda,
                                   hover_name='City',
                                   hover_data=['State', 'Average_Low', 'Average_High', 'Latitude', 'Longitude', 'Record_Low', 'Record_High', 'Wind', 'Elevation', 'Humidity', 'Total_Precip'],
                                   color=sort_by,
                                   color_continuous_scale=px.colors.sequential.Plasma,
                                   zoom=3.4,
                                   opacity=1,
                                   lat='Latitude',
                                   lon='Longitude',
                                   center={'lat': 37.0902, 'lon': -95.7129},
                                   mapbox_style='carto-darkmatter')
        figure.update_layout(margin = {'r':0,'t':0,'l':0,'b':0})
        #figure.update(layout = dict(legend = dict(bgcolor = 'red')))
        return figure.to_json()

Here is something that might be helpful https://plotly.com/python/reference/#layout-showlegend

Goldman answered 23/6, 2020 at 1:32 Comment(0)
F
9

You were pretty close. Just use:

fig.update_layout(legend = dict(bgcolor = 'yellow'))

And you'll get:

enter image description here

Complete code:

import plotly.express as px

df = px.data.gapminder().query("continent=='Oceania'")
fig = px.line(df, x="year", y="lifeExp", color='country')

fig.update_layout(showlegend=True)
fig.update_layout(legend = dict(bgcolor = 'yellow'))

fig.show()
Frons answered 24/6, 2020 at 10:41 Comment(0)
Z
1

fill value according to you

import plotly.express as px
tips = px.data.tips()
fig = px.bar(tips, x='sex', y='total_bill',
             color='smoker', barmode='group')

fig.update_layout({
'plot_bgcolor': 'rgba(0, 0, 0, 0)',
'paper_bgcolor': 'rgba(0, 0, 0, 0)',
})

fig.show()
Zo answered 23/6, 2020 at 2:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.