[Python] Mapping between GeoPandas coordinates and MatPlotLib coordinates

Discussão em 'Python' iniciado por Stack, Julho 9, 2025.

  1. Stack

    Stack Membro Participativo

    I'd like to draw a map with geopandas which I then want to overlay with standard matplotlib plots as subplots.

    map = gpd.read_file("my_shapefile.shp")
    map["values"] = np.random.rand(len(map))
    fig, ax = plt.subplots(1, 1, figsize=(15, 15))
    map.plot(column="values", ax=ax, legend=True, cmap="Reds")

    map["county_centers"] = map.geometry.centroid # With this, I get coordinates
    # of a point in the center of the polygons
    # in "Map"-coordinates


    subax = fig.add_axes([0.45, # left
    0.45, # bottom
    0.1, # width
    0.1]) # height

    subax.pie([0.2,0.8], labels=["A", "B"])
    fig.show()


    It would be great, if I could just use the centroids of the polygons to position my subplots, but they are on a different coordinate system.

    I tried to normalize them:

    minx, miny, maxx, maxy = map.total_bounds

    p = map["county_centers"][0]
    x = (p.x - minx) / (maxx - minx)
    y = (p.y - miny) / (maxy - miny)


    and a variety of different calculations, omitting the subtraction at the on or the other place. All of them ending up outside the map.

    Is there any way, to easily map the centroids to matplotlib coordinates?

    Continue reading...

Compartilhe esta Página