Python plotly_Connection标记线内有标签。

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

在下面的代码中,我有标记标签.现在我想制作连接标记中心和文本的线(见下图)。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=df["longitude"],
              lat=df["latitude"],
              text=df["data"],
              textposition="middle right",
              mode='text',
              showlegend=False))
fig.show()

如果你在经度上加了10,那么地球仪上就会出现反映平行线的弧线。这在大比例尺上或在代码中添加更大的数字时非常明显。enter image description here

python annotations label plotly scatter
1个回答
1
投票

看一下 annotations 选项 我不知道如何使用 update_layout 内的地图。我想到的是在离点有一定距离的地方添加标签(这里我在经度上加了10),然后手动加线。见下图。

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})
df = df.astype({"longitude": float})
df = df.astype({"latitude": float})

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"]+10,
              lat=df["latitude"],
              text=df["data"],
              textposition="middle right",
              mode='text',
              showlegend=False))

for i in range(len(df)):
    fig.add_trace(
        go.Scattergeo(
            lon = [df['longitude'][i], df['longitude'][i]+9],
            lat = [df['latitude'][i], df['latitude'][i]],
            mode = 'lines',
            line = dict(width = 1,color = 'red'),
            showlegend=False
        )
    )


fig.show()

© www.soinside.com 2019 - 2024. All rights reserved.