0

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.

4
  • 1
    Is it the library not drawing correctly or is is a corrupt shapefile, being rendered as well as possible? I'm guessing it's the latter..
    – Vince
    Commented Nov 2, 2019 at 11:47
  • 1
    Welcome to GE, how did you draw your polygons? Can we see your code and data structure? I used patches an pathes for that and i think there is an example in the docs. Commented Nov 2, 2019 at 11:57
  • Thanks for your answers. I provided some additional information in the original post (the data points for the red area and the code for plotting).
    – ftime
    Commented Nov 2, 2019 at 12:49
  • The shapefile specification states that a polygon is composed of one or more rings, and that exterior rings will be clockwise ordered, while interior rings will be counterclockwise (and that interior rings will follow the exterior ring to which they prove an exception). Your code doesn't appear to handle multiple rings at all.
    – Vince
    Commented Nov 2, 2019 at 13:18

1 Answer 1

3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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