Search code examples
pythongeopandasgeoplot

How to add labels in geopandas geoplot?


Let's say I have the following dataset:

import geopandas as gpd
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
world.plot()

What I want to achieve is to plot the data with labels, for instance, to add corresponding values of columns iso_a3 and pop_est as labels on each geometry on the plot.

Thanks


Solution

  • Use a lambda function to plot the labels.

    fig, ax = plt.subplots(figsize=(20, 10))
    world.plot(ax=ax)
    world.apply(lambda x: ax.annotate(text=x['iso_a3'], xy=x.geometry.centroid.coords[0], ha='center'), axis=1)
    

    In this case the labels are plotted in the center of each polygon. In case you want to plot more labels you case use the centroid plus a small offset.