Plotly:在美国的 Choropleth 上写数字

Plotly: Write numbers on Choropleth of the US

对于一项数学作业,我正在研究美国选举团的分布和选民的分布。我解决了一个 LP 根据现在每个州的人口重新定义这个分布。

现在我想在美国地图上绘制我的结果。我用 Plotly 来做到这一点。这是我的代码:

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()

我的问题是我无法写出每个州的选民人数(我知道颜色表示选民人数,但要求必须在每个州写上选民人数)

有人知道我怎样才能写出每个州的选民人数吗?谢谢!

您可以使用散点图覆盖等值线图,如下例所示。

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()