我尝试使用 Scattergeo 绘制美国地图。我有很多彼此靠近的标记,它们的标记文本相互重叠,看起来很混乱。有解决方法吗?我正在努力使地图看起来尽可能干净。
我不一定需要标记位于其精确坐标,但我不想手动调整每个地理坐标,因为坐标太多。所以程序化的东西是最好的。
这是一个棘手的问题。除了缩小字体的明显想法之外,一种可能性是创建一些按钮,其中每个按钮切换相同比例的标记文本标签。如果您有 50 个标记文本标签,则可以使用 10 个按钮,每个按钮切换 5 个标记文本标签,从而减少它们重叠的机会。您可以相应地调整按钮的数量。
下面是一个包含机场数据的示例,否则会有很多重叠的文本:
import numpy as np
import pandas as pd
import plotly.graph_objects as go
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
df['text'] = df['airport'] + '' + df['city'] + ', ' + df['state'] + '' + 'Arrivals: ' + df['cnt'].astype(str)
## assign clusters to data at random
np.random.seed(42)
n_clusters = 10
cluster_choices = [f'Cluster_{i}' for i in range(n_clusters)]
df['cluster'] = np.random.choice(cluster_choices, size=len(df))
fig = go.Figure()
## only show the text for first cluster of markers
for group, df_group in df.groupby('cluster'):
if group == 'Cluster_1':
print("cluster 1 is visible")
visible = True
else:
visible = False
fig.add_trace(go.Scattergeo(
lon = df_group['long'],
lat = df_group['lat'],
text = df_group['airport'],
mode = 'text',
visible = visible
))
## always show markers
fig.add_trace(go.Scattergeo(
lon = df['long'],
lat = df['lat'],
text = df['airport'],
mode = 'markers',
marker_color = df['cnt'],
visible = True,
))
## there are n_clusters text traces, followed by n_clusters marker traces
## so we always show the last n_clusters out of all traces
visible_array = [[i == j for j in range(n_clusters)] + [True]*n_clusters for i in range(n_clusters)]
updatemenus = [
dict(
buttons=[
dict(
label=f'Cluster {i}',
method='update',
args=[{'visible': visible_array[i]},
{'title': f'Cluster {i}'}]
) for i in range(n_clusters)
]
)
]
fig.update_layout(
title = 'Most trafficked US airports<br>(Hover for airport names)',
geo_scope='usa',
showlegend=False,
updatemenus=updatemenus
)
fig.show()