0

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,

Michael Delgado
  • 13,789
  • 3
  • 29
  • 54
  • what are the bounds reported in `countries_gdf.bounds` right after you read the file (before clipping)? If it's in a different CRS, the values may not be inside your polygon bounding box at all, so you could end up with no data at that step. Also worth checking to make sure the results of your query tx have len > 0 – Michael Delgado Jun 08 '22 at 15:13
  • just saw that the image *does* display the states and texas highlight correctly. the issue is just that the annotaion is missing? – Michael Delgado Jun 08 '22 at 15:14

1 Answers1

0

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)
Michael Delgado
  • 13,789
  • 3
  • 29
  • 54