问题
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