[英]Python_Calculative coordinates for labels in Plotly lib
在下面的代码中,我在 map 本身上有标记的标签。
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) + 5 for d in df["longitude"]],
lat=[float(d) + 0 for d in df["latitude"]],
text=df["data"],
textposition="middle right",
mode='text',
showlegend=False))
fig.show()
我把这段代码:
float(d) + 5 for d in df["longitude"]],
lat=[float(d) + 0 for d in df["latitude"]]
使这些标签靠近标记。 但如果调整 map 的大小,这些标签看起来很奇怪。 我相信不仅可以将标签 position 置于现在的绝对值状态,而且还可以将标签坐标和数据值之间的某种依赖关系置于状态。
一种可能对您有用的方法是用空格填充您的df.data
值。 例如,这里的数据在新变量tag
中用三个空格填充。
# tag = [' 15', ' 4', ' 41']
tag = " " + df['data'].astype(str)
fig.add_trace(go.Scattergeo(lon=df["longitude"],
lat=df["latitude"],
text = tag,
textposition="middle right",
mode='text',
showlegend=False))
或使用texttemplate
:
fig.add_trace(go.Scattergeo(lon=df["longitude"],
lat=df["latitude"],
text=df["data"],
textposition="middle right",
mode='text',
showlegend=False,
texttemplate=" %{text}"
))
更新:通过基于df.data
指定可变宽度并使用右对齐,可以使用texttemplate
进行进一步格式化,有关更多选项,请参阅格式规范迷你语言。 就像是:
#text template width based on formula width=x/12+3 and '>' to right justify
tt = ["%{text:>" + str(x/12 + 3) + "}" for x in df['data']]
fig.add_trace(go.Scattergeo(lon=df["longitude"],
lat=df["latitude"],
text=df["data"],
textposition="middle right",
mode='text',
showlegend=False,
texttemplate= tt
))
原来的:
放大:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.