Ahmed3
April 18, 2020, 10:33am
1
Hi everyone !
I was wondering if it is possible to have discrete colors for go.Choroplethmapbox ?
So exactly like this example: https://plotly.com/python/mapbox-county-choropleth/#discrete-colors ,
but with plotly.graph_objects instead of plotly.express ?
go.Choroplethmapbox doesn’t have a ‘color’ attribute like px.choropleth_mapbox.
When I use the ‘z’ attribute I get this item in the legend and since all my “polygons” have the same color, it makes no sense.
Thanks !
Ahmed
Hi @Ahmed3 the plotly express figure is built internally by creating a go.Choroplethmapbox
trace of constant z
, and a dedicated colorscale which has a constant color over the [0, 1]
value range. By the way, you can learn this by doing print(fig)
on the figure created by plotly express. Below is a code snippet reproducing the example figure
import plotly.express as px
df = px.data.election()
geojson = px.data.election_geojson()
colorscales = [
((0.0, '#636efa'), (1.0, '#636efa')),
((0.0, '#EF553B'), (1.0, '#EF553B')),
((0.0, '#00cc96'), (1.0, '#00cc96'))
]
fig = go.Figure()
for i, winner in enumerate(df['winner'].unique()):
dfp = df[df['winner'] == winner]
fig.add_choroplethmapbox(geojson=geojson, locations=dfp['district'],
z=[i,] * len(dfp), featureidkey="properties.district",
showlegend=True, name=winner,
colorscale=colorscales[i], showscale=False)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0},
mapbox=dict(style="carto-positron", zoom=9,
center={"lat": 45.5517, "lon": -73.7073},))
fig.show()
2 Likes
Ahmed3
April 18, 2020, 3:15pm
3
Fantastic !
Thanks a lot Emmanuelle, solved my problem right away !