Geopandas map annotate not visible

312 Views Asked by At

I don't understand why I can't annotate my map of the United States.

import fiona
import geopandas
import matplotlib.pyplot as plt
from shapely.geometry import Polygon,box


countries_gdf = geopandas.read_file("geopkg/USA.gpkg",layer="ADM_1")
polygon = box(-130, -70, 0, 50)
countries_gdf = geopandas.clip(countries_gdf, polygon)

f = plt.figure()
ax = f.add_subplot()

all_states = countries_gdf.plot(facecolor="gray",edgecolor="black",linewidth=.15,rasterized=True)

tx = countries_gdf.query('HASC_1 == "US.TX" or HASC_1 == "US.MI"')
tx.plot(ax=all_states,rasterized=True)
tx.apply(lambda x: ax.annotate(text=x.NAME_1, xy=x.geometry.centroid.coords[0], ha='center'),axis=1)

plt.savefig("test3.png",dpi=500)

The code does not crash and does not display anything.

I use as gpkg file, the one present on this site: https://gadm.org/download_country.html.

Could the problem be the CRS projection system? I also tried to enter the coordinates manually but without results either.

Map without annotation

Thank you in advance,

1

There are 1 best solutions below

0
On

Make sure to use the figure and axis objects you create consistently through the various plots and annotations. It looks like you were creating a new plot with countries_gdf.plot (ignoring fig and ax), but then using the original ax to annotate.

import fiona
import geopandas
import matplotlib.pyplot as plt
from shapely.geometry import Polygon,box

countries_gdf = geopandas.read_file("geopkg/USA.gpkg",layer="ADM_1")
polygon = box(-130, -70, 0, 50)
countries_gdf = geopandas.clip(countries_gdf, polygon)

f = plt.figure()
ax = f.add_subplot()

# make sure you plot all states using ax
countries_gdf.plot(
    facecolor="gray", edgecolor="black", linewidth=.15, rasterized=True,
    # add this
    ax=ax,
)

tx = countries_gdf.query('HASC_1 == "US.TX" or HASC_1 == "US.MI"')
tx.plot(ax=ax, rasterized=True)
tx.apply(
    lambda x: ax.annotate(
        text=x.NAME_1,
        xy=x.geometry.centroid.coords[0],
        ha='center',
    ),
    axis=1,
)

fig.savefig("test3.png",dpi=500)