Python plotly_Connection markers with labels within line

百般思念 提交于 2020-06-13 06:00:08

问题


In the code below I have marker labels. Now I want to make lines which connect center of markers with text (see pic below).

What is the way to make it?

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

In case you added 10 to the longitude, there appered arcs reflecting parallels on the globe. It's very visible on big scale or whent you add bigger figures in code.


回答1:


Looking at the annotations options I couldn't figure out how to use update_layout within the maps. What I think of was adding the labels at some distance (here, I added 10 to the longitude) from the points and then adding the lines manually. See below;

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



来源:https://stackoverflow.com/questions/61937245/python-plotly-connection-markers-with-labels-within-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!