密谋:如何在散点图中自定义标签?

时间:2020-05-21 16:51:07

标签: python text label plotly marker

在下面的代码中,我有标记标签,这些标记现在靠近这些标记。在标记与其标签之间进行自定义目标的方法是什么?我现在想将标签离标记稍远一些。

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()

1 个答案:

答案 0 :(得分:1)

我看到您正在使用第二条Scattergeo跟踪来显示标签。这似乎不是一个坏主意,因为在我看来fig.add_annotationpx.scatter_geo图中可能有些棘手。因此,我只需稍微调整纬度和经度数即可将标签放置在您喜欢的位置,例如lon=[float(d) + 10 for d in df['longitude']]

enter image description here

完整代码:

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()