在地图上放置悬停注释

问题描述 投票:0回答:1

我编写了以下代码,它可以实现我想要的功能,但是在美国地图上。

import plotly.express as px
import pandas as pd

Counties = pd.read_excel('/content/uscounties.xlsx')
data = Counties[Counties['state_name'] == 'Georgia']


fig = px.scatter_geo(data, lat='lat', lon='lng', color='county',
                     hover_name='county', scope='usa',
                     title='Georgia Counties')
fig.show()

我想要在乔治亚州地图上使用此代码,但我不知道如何更改地图。

我尝试了使用乔治亚地图的不同代码,但悬停注释不显示:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(15, 15))

shapefile.plot(ax=ax, alpha=0.4, color='green')

geo_gc1.plot(ax=ax,
             markersize=20,
             color='blue',
             marker='o')

hover_text = {row['geometry']: row['county'] for index, row in geo_gc1.iterrows()}

for x, y, county in zip(geo_gc1.geometry.x, geo_gc1.geometry.y, geo_gc1['county']):
    ax.annotate(county, xy=(x, y), textcoords="offset points", xytext=(5, 5), ha='left')

plt.legend(prop={'size': 10})

plt.show()

我已经尝试了很多,但无法找出问题所在。我知道形状文件上的悬停注释是不同的。我怎样才能做到这一点?

python matplotlib plotly
1个回答
0
投票

由于未提供您的数据,我从代码中进行了有根据的猜测。我从here获取了乔治亚州的geojson文件,并使用geopandas来构建数据。我给它添加了纬度和经度。我获取了乔治亚州中心的纬度和经度,并设置了地图的中心。我们添加了 fitbouneds='locations' 来限制地图的区域。 最后,由于图例数量非常多,我们将其移至地图底部并水平创建。 为了可视化,可能需要按县进行绘制。

import geopandas as gpd

geojson_path = './data/georgia-with-county-boundaries_1092.geojson'

gdf = gpd.read_file(geojson_path, driver='GeoJSON')
gdf["lng"] = gdf.centroid.map(lambda p: p.x)
gdf["lat"] = gdf.centroid.map(lambda p: p.y)

import plotly.express as px

fig = px.scatter_geo(gdf,
                     lat='lat',
                     lon='lng',
                     color='name',
                     hover_name='name',
                     scope='usa',
                     title='Georgia Counties')

fig.update_layout(geo=dict(center=dict(lat=33.748, lon=-84.388), fitbounds='locations'))
fig.update_layout(height=800, width=750, margin=dict(r=0,t=30,l=0,b=0))
fig.update_layout(legend=dict(yanchor='bottom', y=-0.6, xanchor='left', x=0.01, orientation='h'))

fig.show()

© www.soinside.com 2019 - 2024. All rights reserved.