簡體   English   中英

Plotly 庫中標簽的 Python_Calculative 坐標

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM