简体   繁体   中英

Plotly: Write numbers on Choropleth of the US

For a math assignment I'm working on the distribution of the Electoral College of the US and on the distribution of the electors. I solve a LP to redefine this distribution according to nowadays population in each state.

Now I want to plot my results on a map of the US. I used Plotly to do that. Here is my code :

import plotly.graph_objects as go

locations = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY",
             "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND",
             "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WV", "WA", "WI", "WY"]
colors = [8.0, 3.0, 11.0, 5.0, 61.0, 9.0, 6.0, 3.0, 3.0, 33.0, 17.0, 3.0, 3.0, 20.0, 11.0, 5.0, 5.0, 7.0, 8.0, 3.0,
          10.0, 11.0, 16.0, 9.0, 5.0, 10.0, 3.0, 3.0, 5.0, 3.0, 14.0, 4.0, 31.0, 16.0, 3.0, 19.0, 7.0, 7.0, 20.0, 3.0,
          8.0, 3.0, 11.0, 44.0, 5.0, 3.0, 14.0, 12.0, 3.0, 9.0, 3.0]


fig = go.Figure(data=go.Choropleth(locations=locations, locationmode="USA-states", z=colors, colorscale="Reds"))

fig.update_layout(
    geo = dict(
        scope='usa',
        projection=go.layout.geo.Projection(type = 'albers usa')))
fig.show()

My problem is that I'm not able to write the number of electors on each state (I know that the color indicate the number of electors but it is a requirement that the number of elector must be written on each state)

Does someone know how I can write the number of electors on each state ? Thank you !

You could overlay the choropleth map with a scattergeo as in the example below.

import plotly.graph_objects as go

locations = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS",
             "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC",
             "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WV", "WA", "WI", "WY"]

electors = [8, 3, 11, 5, 61, 9, 6, 3, 3, 33, 17, 3, 3, 20, 11, 5, 5, 7, 8, 3, 10, 11, 16, 9, 5, 10, 3, 3, 5, 3, 14,
            4, 31, 16, 3, 19, 7, 7, 20, 3, 8, 3, 11, 44, 5, 3, 14, 12, 3, 9, 3]

layout = dict(font=dict(size=8), geo=dict(scope="usa", projection=dict(type="albers usa")))

data = []

data.append(go.Choropleth(locations=locations, z=electors, locationmode="USA-states", colorscale="Reds"))
data.append(go.Scattergeo(locations=locations, text=electors, locationmode="USA-states", mode="text"))

fig = go.Figure(data=data, layout=layout)

fig.show()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM