60

我想将 Shapely 用于我的计算几何项目。为此,我需要能够可视化和显示多边形、线条和其他几何对象。我已经尝试为此使用 Matplotlib,但我遇到了麻烦。

from shapely.geometry import Polygon
import matplotlib.pyplot as plt

polygon1 = Polygon([(0,5),
                    (1,1),
                    (3,0),
                    ])

plt.plot(polygon1)
plt.show()

我希望能够在绘图中显示这个多边形。我将如何更改我的代码来做到这一点?

4

8 回答 8

97

利用:

import matplotlib.pyplot as plt

x,y = polygon1.exterior.xy
plt.plot(x,y)

或者,更简洁地说:

plt.plot(*polygon1.exterior.xy)
于 2019-05-15T00:10:56.257 回答
29

有点晚了,但我发现最方便的方法是使用上面建议的 Geopandas,但无需先写入文件。

from shapely.geometry import Polygon
import matplotlib.pyplot as plt
import geopandas as gpd

polygon1 = Polygon([(0,5),
                    (1,1),
                    (3,0),
                    ])

 p = gpd.GeoSeries(polygon1)
 p.plot()
 plt.show()

使用 Geopandas 绘制的多边形

查看Geopandas.GeoSeries的文档

于 2020-07-10T15:13:58.477 回答
7

如果您的数据在.shp文件中,我会推荐 geopandas:

import geopandas as gpd
import matplotlib.pyplot as plt

shapefile = gpd.read_file("path/to/shapes.shp")
shapefile.plot()
plt.show()

于 2020-01-10T20:48:46.850 回答
2

这可能是一种矫枉过正,但作为其他好的评论的替代品,我会添加一个安装 QGIS 的选项 - 一个用于处理几何图形的免费软件。您需要做的就是将几何图形保存为形状文件 (.shp)、geoJSON 或任何其他格式,然后使用 QGIS 打开它。如果你正在计划一个大项目,最后可能比使用 matplotlib 更方便。

于 2019-04-05T14:00:48.817 回答
2

我厌倦了 Matplotlib 用于创建这些绘图图像的 janky API,所以我创建了自己的库。Python 模块称为WKTPlot,它使用Bokeh制作数据的交互式绘图。我有关于如何绘制 WKT 字符串数据以及来自 Shapefile 的数据的示例。

它支持所有最匀称的几何类型:

  • 观点
  • 多点
  • 线串
  • 多行字符串
  • 线性环
  • 多边形
  • 多多边形
  • 几何集合
于 2021-08-13T23:53:41.607 回答
1

几何图形可以是Point, LineString, Polygon, 以及它们的集合版本MultiPoint, MultiLineString, MultiPolygon.

观点

只需将坐标传递给pyplot

points = (point1, point2, point3, point3D)
xs = [point.x for point in points]
ys = [point.y for point in points]

fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.scatter(xs, ys)

线串

只需将 x 和 y 集合传递给pyplot. 它们是使用xy属性获得的。此属性返回如下内容:

(array('d', [3.0, 2.0, 9.0]), array('d', [6.0, -1.0, 4.0]))

并且可以这样使用:

ax.plot(line.xy[0], line.xy[1])
ax.plot(*line.xy) # Equivalent

多边形

对于Polygon当前接受的答案确实只适用于退化的多边形,即没有孔的多边形。这是一个适用于任何多边形的版本,具有颜色和其他属性的常用关键字。这不是我的设计,它只是改编自GeoPandas 源

import numpy as np
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from matplotlib.collections import PatchCollection


# Plots a Polygon to pyplot `ax`
def plot_polygon(ax, poly, **kwargs):
    path = Path.make_compound_path(
        Path(np.asarray(poly.exterior.coords)[:, :2]),
        *[Path(np.asarray(ring.coords)[:, :2]) for ring in poly.interiors])

    patch = PathPatch(path, **kwargs)
    collection = PatchCollection([patch], **kwargs)
    
    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    return collection

它是这样使用的:

from shapely.geometry import Polygon
import matplotlib.pyplot as plt


# Input polygon with two holes
# (remember exterior point order is ccw, holes cw else
# holes may not appear as holes.)
polygon = Polygon(shell=((0,0),(10,0),(10,10),(0,10)),
                  holes=(((1,3),(5,3),(5,1),(1,1)),
                         ((9,9),(9,8),(8,8),(8,9))))

fig, ax = plt.subplots()
plot_polygon(ax, polygon, facecolor='lightblue', edgecolor='red')

在此处输入图像描述

收藏品

对于Multi- 集合,只需在每个元素上调用 plot 函数。

于 2021-12-30T14:35:02.740 回答
1

您还可以“跟随” Shapely 用户手册中的源代码:(单击“源代码”)。

这里提供的“源代码”不是实际的 Shapely 源代码,而是用户手册中用于创建示例的代码。使用 Shapely 用户手册中的“示例代码”,您可以快速创建具有相同友好风格的图像。

https://shapely.readthedocs.io/en/latest/manual.html#linestrings 2021 年 11 月的屏幕截图

您将需要“图形”模块,它只是一个简短的、非常简单的 python 文件,来自:https ://github.com/Toblerity/Shapely/blob/main/docs/code/figures.py 。(取自https://gis.stackexchange.com/questions/362492/shapely-examples-use-figures-what-is-this-library

于 2021-11-29T10:49:53.470 回答
1

这是一个使用 matplotlib 补丁的解决方案,它也解释了漏洞:

import numpy as np
import shapely.geometry as sg
import matplotlib.pyplot as plt
import matplotlib.patches as patches


def add_polygon_patch(coords, ax, fc='blue'):
    patch = patches.Polygon(np.array(coords.xy).T, fc=fc)
    ax.add_patch(patch)


border = [(-10, -10), (-10, 10), (10, 10), (10, -10)]  # Large square
holes = [
    [(-6, -2), (-6, 2), (-2, 2), (-2, -2)],  # Square hole
    [(2, -2), (4, 2), (6, -2)]               # Triangle hole
]
region = sg.Polygon(shell=border, holes=holes)

fig, ax = plt.subplots(1, 1)

add_polygon_patch(region.exterior, ax)
for interior in region.interiors:
    add_polygon_patch(interior, ax, 'white')
        
ax.axis('equal')
plt.show()

带有多边形孔的多边形区域

于 2021-11-09T19:17:36.933 回答