为什么在检查点是否在多边形内时,patch.contains_point()的行为与patch.get_path().c



使用matplotlib.patches,patch.contains_point(xy)方法的工作方式似乎与patch.get_path().contains_point(xy)不同,至少在将补丁添加到轴之后是这样。见下文True/TrueTrue/False的差异。我找不到任何关于这种差异的文件。有人知道吗?我也很难理解contains_point()是如何决定点是否在路径内的,因为在这种情况下,路径的顶点是单位矩形,而不是我指定的矩形。

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

虽然这个问题很老,但我只是面对同样的问题并解决了它。

问题是在向轴添加补丁后,需要在显示参考系中给出坐标/点。这可以通过以下方式执行:

ax.transData.transform()

我在代码中添加了一行忽略导入语句。代码在这里:

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

相关内容

  • 没有找到相关文章

最新更新