TransWikia.com

Plotting polygons as separate plots using Python

Geographic Information Systems Asked by Ralt_Jol on June 23, 2021

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.

3 Answers

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

Correct answer by Kadir Şahbaz on June 23, 2021

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 ;)

Answered by s.k on June 23, 2021

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

Answered by Kadir Şahbaz on June 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP