matplotlib 为什么patch.contains_point()在检查点是否在多边形内时与patch.get_path().contains_point()的行为不同?

s4n0splo  于 2022-12-04  发布在  其他
关注(0)|答案(1)|浏览(91)

对于matplotlib.patches,patch.contains_point(xy)方法的工作方式似乎与patch.get_path().contains_point(xy)不同,至少在将补丁添加到轴上之后是这样的。请参见下面的True/TrueTrue/False的区别。我找不到任何关于这个区别的文档。有人知道吗?我也很难看到contains_point()如何确定该点是否在给定路径的路径内。在这种情况下,s的顶点是单位矩形,而不是我指定的矩形。

fig, ax = plt.subplots()
rect = patches.Rectangle([0.2, 0.3], 0.8, 0.5)

pnt = [0.4, 0.45] # point inside rect
print("Before adding patch to axes:")
print(rect.get_path().vertices)
print(rect.contains_point(pnt))
print(rect.get_path().contains_point(pnt))

print("After adding patch to axes")
ax.add_patch(rect)
print(rect.get_path().vertices)
print(rect.contains_point(pnt))
print(rect.get_path().contains_point(pnt))

plt.show()

Before adding patch to axes:
[[0. 0.]
 [1. 0.]
 [1. 1.]
 [0. 1.]
 [0. 0.]]
True
True
After adding patch to axes
[[0. 0.]
 [1. 0.]
 [1. 1.]
 [0. 1.]
 [0. 0.]]
False
True
9wbgstp7

9wbgstp71#

虽然这个问题是老问题,但我刚刚面对同样的问题并解决了它。
问题是在将面片添加到轴后,您需要在显示参考框架中给予坐标/点。这可以通过以下方式执行:

ax.transData.transform()

我在代码中添加了一行忽略import语句的代码,代码如下所示:

import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig, ax = plt.subplots()
rect = patches.Rectangle([0.2, 0.3], 0.8, 0.5)

pnt = [0.4, 0.45] # point inside rect
print("Before adding patch to axes:")
print(rect.get_path().vertices)
print(rect.contains_point(pnt))
print(rect.get_path().contains_point(pnt))

print("After adding patch to axes")
ax.add_patch(rect)
print(rect.get_path().vertices)
# added lines
pnt_in_display_coordiantes = ax.transData.transform(pnt)
print(rect.contains_point(pnt_in_display_coordiantes))
print(rect.get_path().contains_point(pnt))

plt.show()

输出量:

Before adding patch to axes:
[[0. 0.]
[1. 0.]
[1. 1.]
[0. 1.]
[0. 0.]]
True
True
After adding patch to axes
[[0. 0.]
[1. 0.]
[1. 1.]
[0. 1.]
[0. 0.]]
True
True

更多信息:https://matplotlib.org/stable/tutorials/advanced/transforms_tutorial.html

相关问题