matplotlib中"closed"路径参数的含义

Meaning of "closed" Path parameter in matplotlib

一个基本问题,但我还没有看到关于 SO 的答案。 matplotlib.path库中创建Path对象时的closed参数自带说明:“If codes is None and closed is True, vertices will be treated as line segments一个封闭的多边形。”我不知道这是否意味着您应该在实例化具有已关闭的顶点集的路径时键入 closed=True,或者当您希望为您关闭一组打开的顶点时是否应该键入 closed=True。

此外,according to the docscontains_point()contains_points() 函数“return(闭合)路径是否包含给定点。”

为什么函数 return 无论提供的顶点是否满足关闭条件 AND/OR 的“关闭”参数 = True,结果都是一样的?

情况一:顶点闭合,闭合参数默认为false

In [2]: pth = path.Path([[0,0],[1,0],[1,1],[0,1],[0,0]])
In [3]: pth.contains_point([0.5,0.5])
Out[3]: True

情况2:顶点闭合,闭合参数为true

In [2]:  pth = path.Path([[0,0],[1,0],[1,1],[0,1],[0,0]],closed=True)
In [3]:  pth.contains_point([0.5,0.5])
Out[3]:  True

情况三:顶点打开,关闭参数默认为false

In [2]:  pth = path.Path([[0,0],[1,0],[1,1],[0,1]])
In [3]:  pth.contains_point([0.5,0.5])
Out[3]:  True

情况4:顶点打开,关闭参数true

In [2]:  pth = path.Path([[0,0],[1,0],[1,1],[0,1]],closed=True)
In [3]:  pth.contains_point([0.5,0.5])
Out[3]:  True

所有示例条件均由以下代码重现,清楚说明为什么 contains_point([0.5,0.5]) 总是返回 True。一个不幸的巧合,误解了 Path 对象认为什么是路径的内部以及测试点的位置:

import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches

fig, axes = plt.subplots(2, 2, figsize=(10, 10))

point1 = [0.5, 0.5]
point2 = [0.3, 0.7]

titles = ["Case 1\nVertices closed, closed parameter false by default",
          "Case 2\nVertices closed, closed parameter true",
          "Case 3\nVertices open, closed parameter false by default",
          "Case 4\nVertices open, closed parameter true"]

paths = [Path([[0,0],[1,0],[1,1],[0,1],[0,0]],closed=True),
         Path([[0,0],[1,0],[1,1],[0,1],[0,0]]),
         Path([[0,0],[1,0],[1,1],[0,1]]),
         Path([[0,0],[1,0],[1,1],[0,1]],closed=True)]

for ax, t, p in zip(axes.flat, titles, paths):
    patch = patches.PathPatch(p, facecolor="orange", lw=2, zorder=0)
    ax.add_patch(patch)
    ax.scatter(*point1, label="Path contains point {}: {}".format(point1, p.contains_point(point1)))
    ax.scatter(*point2, label="Path contains point {}: {}".format(point2, p.contains_point(point2)))
    ax.set_title(t)
    ax.legend()

plt.tight_layout()
plt.show()

输出:

带回家的留言: