Search code examples
pythonplotly

Plotly: how to add data labels to a Choropleth


I have the following Pandas dataframe df that looks as follows:

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

I'd like to be able to create a Plotly choropleth that includes data labels over each of the states.

To do so, I use 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()

enter image description here

But, using add_scattergeo does not apply the desired labels.

What's the best way to add data labels to a Plotly choropleth?

Thanks!


Solution

  • You need to also add locationmode="USA-states" to 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',
    )
    

    Output:

    enter image description here