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:
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)
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.
-
1Is 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– Vince2019年11月02日 11:47:48 +00:00Commented Nov 2, 2019 at 11:47
-
1Welcome 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.Andreas Müller– Andreas Müller2019年11月02日 11:57:50 +00:00Commented 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– ftime2019年11月02日 12:49:40 +00:00Commented 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– Vince2019年11月02日 13:18:47 +00:00Commented Nov 2, 2019 at 13:18
1 Answer 1
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()
Zoom to see the island
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()