Search code examples
pythonmatplotlibplotly

Put hovering annotations on a map


I made the following code, which does what I want, but on a USA Map.

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()

I would like this code on a map of Georgia, but I can't figure out how to change the map.

I tried different code that uses a Georgia map but the hover annotations don't 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()

I've tried a lot but can't figure out the issue. I know hovering annotations on shapefiles is different. How can I make this work?


Solution

  • Since your data was not presented, I made an educated guess from the code. I got the geojson file for Georgia from here and used geopandas to frame the data. I added latitude and longitude to it. I got the latitude and longitude of the center of Georgia and set the center of the map. We added fitbouneds='locations' to limit the area of the map. Finally, since the legend count is very large, we moved it to the bottom of the map and created it horizontally. For visualization, it may be desirable to paint by county.

    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()
    

    enter image description here