Add outline to discrete choropleth legend items in plotly python

Viewed 522

I am currently making a discrete choropleth map using plotly and Python. Is there a way to add a border/outline around each color in the legend? Most of the solutions I've seen so far just address borders for markers, which is not what I want since this is a choropleth map. If I update the traces for the markers, it'll just affect how the country outlines look like on the map but won't change the legend at all.

I understand that there are ways to change the layout for the legend overall or add an outline to the legend box overall, but I haven't seen anything on outlines for each individual color/legend item. Is this possible, or will it require a workaround?

My code for the discretely colored choropleth map is similar to what's in the plotly graphing library (https://plotly.com/python/choropleth-maps/#discrete-colors):

import plotly.express as px

df = px.data.election()
geojson = px.data.election_geojson()

fig = px.choropleth(df, geojson=geojson, color="winner",
                    locations="district", featureidkey="properties.district",
                    projection="mercator", hover_data=["Bergeron", "Coderre", "Joly"]
                   )
fig.update_geos(fitbounds="locations", visible=False)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

Right now, the map looks like this: current map

But I'd like to add outlines around each of the colored squares in the legend, kind of like in the legend on the right in this image:

desired legend

1 Answers

If you want a discrete legend wth continuous data you can add a new column to you dataframe with a string representation of what you want to be displayed in the legend.

For example in the picture below I have data as numbers in the column "REL" and I wanted the legend to show intervals in percentages so I created a new column with the ranges written in strings and then set the px.choropleth(color="REL_RANGE, ...)

enter image description here

You can use df.apply() for this. Check this tutorial https://mahshadn.medium.com/animated-choropleth-map-with-discrete-colors-using-python-and-plotly-styling-5e208e5b6bf8

Related