TransWikia.com

Plot shapefile with islands with matplotlib

Geographic Information Systems Asked by ftime on August 13, 2021

I am trying to plot a city shapefile with matplotlib’s plt.plot()-function. However, within the closed areas I occasionally have small “islands” which lie within the city but not part of it. Therefore I have a solid line connecting one part to “island” as can be seen in the red area:

City borders

Any idea how I can prevent this from happening?

Update:

The points for the coloured area looks like this: https://textuploader.com/1kv27
(full shape-data can be downloaded here: https://www.suche-postleitzahl.org/download_files/public/plz-gebiete.shp.zip)

enter image description here

and is plotted with

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca()
x = [i[0] for i in points][:]
y = [i[1] for i in points][:]
ax.plot(x, y, 'k')

I do face the same problem when I want to plot a state which has islands, the islands will be connected to the mainland with a line.

One Answer

With a polygons shapefile, look at Plot shapefile with matplotlib

You need to use matplotlib paths and patches and there is a Python module dedicated to plot polygons from shapefiles using these functions Descartes.

With your problematic Polygon (directly extracted from the shapefile and not build with your points)

from descartes import PolygonPatch
BLUE = '#6699cc'
GRAY = '#999999'
fig = plt.figure() 
ax = fig.gca() 
ax.add_patch(PolygonPatch(poly, fc=GRAY, ec=BLUE, alpha=0.5, zorder=2 ))
ax.axis('scaled')
plt.show()

enter image description here

Zoom to see the island

enter image description here

You can also directly use GeoPandas (uses Descartes)

import geopandas as gpd
df = gpd.read_file("extract_plz-gebiete.shp")
fig, ax = plt.subplots()
df.plot(ax=ax,color='white', edgecolor='black')
ax.set_aspect('equal')
plt.show()

enter image description here

Answered by gene on August 13, 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