7

I have a shapefile with several polygons in a geodataframe. I want to plot each individual polygon in their own plot.

I tried

for pol in z3:
  plt.figure()
  plt.plot(pol)
  plt.show()

But this just loops through the columns of the data frame.

2
  • What do you mean by "individual plots"? One plot including polygon subplots or separate images? Jan 18 at 22:09
  • I mean separate images, as in one plot for each polygon
    – Ralt_Jol
    Jan 18 at 22:10
10

You can defined a plotting function and then call it on your GeoDataFrame.

Let's dive into an example.

Here are 4 polygons in a Shapefile (drawn with ♥ in QGIS):

QGIS polygons

First do some imports:

import geopandas as gpd
import matplotlib.pyplot as plt
# Load shapefile with geopandas
poly_gdf = gpd.read_file('polygons.shp')

Then, define a plotting function:

def plot_poly_gdf(polygon):
    p = gpd.GeoSeries(poly['geometry'])
    fig, ax = plt.subplots(figsize = (10,10))
    ax.xaxis.set_tick_params(labelsize=14)
    ax.yaxis.set_tick_params(labelsize=14)
    p.plot(color='skyblue', alpha=0.6, ax=ax)
    plt.xlabel(poly['name'], fontsize=20)
    plt.axis('equal')
    plt.grid()

And finally iterate over your GeoDataFrame, calling the previously defined function on each feature:

for i, poly in poly_gdf.iterrows():
    plot_poly_gdf(poly)

Results: Results

Feel more creative than I did on your plotting ;)

1
  • thank you so much!
    – Ralt_Jol
    Jan 19 at 21:47
10
import geopandas as gpd
import matplotlib.pyplot as plt

gdf = gpd.read_file("path/to/shapefile.shp")

for row in gdf.iterrows():    
    geom = gpd.GeoSeries(row[1].geometry)
    geom.plot()

enter image description here

enter image description here

1
  • Thank you so much this worked!
    – Ralt_Jol
    Jan 19 at 21:47
8
import geopandas as gpd
import matplotlib.pyplot as plt

gdf = gpd.read_file("path/to/shapefile.shp")

for row in gdf.iterrows():
    plt.figure(figsize=(5,5))
    plt.axis('equal')
    x, y = row[1].geometry.exterior.xy
    plt.plot(x, y)

This script plots polygon's boundary.

Shapefile:

enter image description here

Separate Plots:

enter image description here

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.