pythonlabelplotlyscatter

Python plotly.express - add labels in scatter_geo


I need to add static labels on markers in scatter_geo vizualization. I added text='data', but nothing had happend:

import plotly.express as px
import pandas as pd

rows=[['501-600','15','122.58333','45.36667'],
      ['till 500','4','12.5','27.5'],
      ['more 1001','41','-115.53333','38.08'],
      ]

colmns=['bins','data','longitude','latitude']
df=pd.DataFrame(data=rows, columns=colmns)
df = df.astype({"data": int})

fig=px.scatter_geo(df,lon='longitude', lat='latitude',
                      color='bins',
                      text='data',
                      opacity=0.5,size='data',
                      projection="natural earth")

fig.show()
fig.write_html('first_figure.html', auto_open=True)

Solution

  • You are an update_trace away from a solution. With go.Scattergeo you can use the parameters mode and textposition inside the method while with plotly.express you should change after.

    import plotly.express as px
    import pandas as pd
    
    rows=[['501-600','15','122.58333','45.36667'],
          ['till 500','4','12.5','27.5'],
          ['more 1001','41','-115.53333','38.08'],
          ]
    
    colmns=['bins','data','longitude','latitude']
    df=pd.DataFrame(data=rows, columns=colmns)
    df = df.astype({"data": int})
    
    fig=px.scatter_geo(df,lon='longitude', lat='latitude',
                          color='bins',
                          text='data',
                          opacity=0.5,
                          size='data',
                          projection="natural earth")
    # This
    fig.update_traces(textposition="top center",
                      mode='markers+text')
    
    fig.show()
    

    ** UPDATE**

    A possible solution in order to avoid the problems in legend is

    import plotly.express as px
    import plotly.graph_objs as go
    import pandas as pd
    
    rows=[['501-600','15','122.58333','45.36667'],
          ['till 500','4','12.5','27.5'],
          ['more 1001','41','-115.53333','38.08'],
          ]
    
    colmns=['bins','data','longitude','latitude']
    df=pd.DataFrame(data=rows, columns=colmns)
    df = df.astype({"data": int})
    
    fig=px.scatter_geo(df,lon='longitude', lat='latitude',
                          color='bins',
                          opacity=0.5,
                          size='data',
                          projection="natural earth")
    
    fig.add_trace(go.Scattergeo(lon=df["longitude"],
                  lat=df["latitude"],
                  text=df["data"],
                  textposition="middle center",
                  mode='text',
                  showlegend=False))
    fig.show()