Search code examples
pythonplotlyvisualizationplotly-python

How to add text labels to a bubble map plot in Python?


I am trying to build a bubble map plot using Python with text labels. I thought that there would be a simple way to do this without too much code.

So far, I have created the plot here using scatter_mapbox() from Plotly Express.

Here is the code that you may use to create the same plot, by updating the token variable with your Mapbox access token:

import plotly
import plotly.express as px
import pandas as pd

df = pd.DataFrame(dict(CityName=['New York', 'Boston'], Latitude=[40.7128, 42.3601], Longitude=[-74.0060, -71.0589], Total=[100,200]))

token = 'PASTE YOUR TOKEN HERE'
px.set_mapbox_access_token(token)

fig = px.scatter_mapbox(df, lat='Latitude', lon='Longitude', hover_name='CityName', size='Total')

plotly.offline.plot(fig)

Is there an easy way for me to modify the code so that I can have a "100" text label above the bubble for New York and a "200" text label above the bubble for Boston, to avoid forcing the user to hover over each bubble to obtain this information?

I tried various things, such as:

  • go.Scattermapbox(), which requires "import plotly.graph_objects as go"
  • fig.add_trace(go.Scattermapbox())
  • fig.update_layout()
  • fig.add_annotation()

But I, personally, wasn't able to get any of them to work.


Solution

  • You can add text to px.scatter_mapbox(). If given in string and list format, it will overlay the numbers on top of the markers. If you want to decorate that text, update the graph.

    import plotly
    import plotly.express as px
    import pandas as pd
    
    df = pd.DataFrame(dict(CityName=['New York', 'Boston'], Latitude=[40.7128, 42.3601], Longitude=[-74.0060, -71.0589], Total=[100,200]))
    
    px.set_mapbox_access_token(open('mapbox_api_key.txt').read())
    
    fig = px.scatter_mapbox(df,
                            lat='Latitude',
                            lon='Longitude',
                            hover_name='CityName',
                            size='Total',
                            text=[str(x) for x in df['Total']],
                            zoom=6
                           )
    
    #plotly.offline.plot(fig)
    fig.update_layout(height=500, font=dict(size=20, color='red'))
    fig.show()
    

    enter image description here