Plotly:如何向 Choropleth 添加数据标签

equ*_*ity 2 python plotly

我有以下Pandas数据框df,如下所示:

import pandas as pd
df = pd.DataFrame({'state' : ['NY', 'CA', 'FL', 'NJ', 'TX', 'CT', 'MA', 'WA', 'IL', 'GA'],
                   'user_id' : [10000, 3200, 1600, 1200, 800, 600, 400, 350, 270, 260]
                        })

    state   user_id
0   NY      10000
1   CA      3200
2   FL      1600
3   NJ      1200
4   TX      800
5   CT      600
6   MA      400
7   WA      350
8   IL      270
9   GA      260
Run Code Online (Sandbox Code Playgroud)

我希望能够创建一个 Plotly choropleth,其中包含每个州的数据标签。

为此,我使用add_scattergeo

fig = px.choropleth(df,
                    locations = 'state', 
                    locationmode = "USA-states", 
                    scope = "usa",
                    color = 'user_id',
                    color_continuous_scale = "blues",
                    )
fig.add_scattergeo(
                   locations = df['state'],
                   text = df['user_id'],
                   mode = 'text',
                   )

fig.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但是,使用add_scattergeo并没有应用所需的标签。

将数据标签添加到 Plotly 分区统计图的最佳方法是什么?

谢谢!

小智 5

您还需要locationmode="USA-states"添加add_scattergeo

fig = px.choropleth(
    df,
    locations='state', 
    locationmode="USA-states", 
    scope="usa",                    
    color='user_id',
    color_continuous_scale="blues",
)
fig.add_scattergeo(
    locations=df['state'],
    locationmode="USA-states", 
    text=df['user_id'],
    mode='text',
)
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述