Search code examples
pythontextlabelplotlymarker

Plotly: How to customize labels in a scattergeo plot?


In the code below I have marker labels which now is located close to these markers. What is the way to make customise destination between marker and it's label? I want to put labels a little bit far from markers now.

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.update_traces(hovertemplate ='bins')

fig.add_trace(go.Scattergeo(lon=df["longitude"],
              lat=df["latitude"],
              text=df["data"],
              textposition="middle right",
              mode='text',
              showlegend=False))
fig.show()

Solution

  • I see you're using a second Scattergeo trace to display your labels. And this does not seem to be a bad idea since it seems to me that fig.add_annotation can be bit tricky in a px.scatter_geo figure. So I would simply adjust the latitude and longitude numbers slightly to get the labels in the positions you prefer, like lon=[float(d) + 10 for d in df['longitude']]:

    enter image description here

    Complete code:

    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.update_traces(hovertemplate ='bins')
    
    fig.add_trace(go.Scattergeo(lon=[float(d) + 10 for d in df['longitude']],
                                  lat=[float(d) - 10 for d in df['latitude']],
                                  text=df["data"],
                                  textposition="middle right",
                                  mode='text',
                                  showlegend=False))
    fig.show()