情节:如何在散点图中自定义标签?

问题描述 投票:1回答:1

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

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()
python text label plotly marker
1个回答
0
投票

我看到您正在使用第二个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()
© www.soinside.com 2019 - 2024. All rights reserved.