【发布时间】:2018-03-04 18:37:21
【问题描述】:
我正在使用 matplotlib.patches.Polygon 来更新图表上的一些彩色补丁,并且我在代码的每次迭代中都这样做。由于我已经以这种方式在代码中定义了补丁,因此我想使用 函数 contains_point() 来判断一个点是否在 补丁或外部。到目前为止,似乎工作的东西是匀称的——但我不想这样做,我宁愿继续使用 matplotlib。调用 add_patch() 后出现问题:在这种情况下,patch 将返回相同的坐标,但函数 contains_point() 不会返回正确的值
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib import gridspec
import numpy as np
让我们定义一些我们想要添加补丁的轴
gs = gridspec.GridSpec(1,1)
axx = [plt.subplot(g) for g in gs]
我们来看看axx是什么类型:
In[84]: axx
Out[84]: [<matplotlib.axes._subplots.AxesSubplot at 0x7fd4b3409cd0>]
现在让我们定义一个带有顶点v 的补丁b
v =
np.array([[ 6.89 , -10.00907385],
[ 5.11 , -10.00907385],
[ 5.11 , -14.68307385],
[ 6.89 , -14.68307385],
[ 6.89 , -10.00907385]])
b = [patches.Polygon(v, color = (0,0,1))]
我们可以测试一下:
In[86]: b[0].contains_point((5.5,-12))
Out[86]: True
现在让我们将补丁添加到之前初始化的子图中
axx[0].add_patch(b[0])
让我们再次测试同一点 (5.5,-12) 是否属于补丁 b
In[88]: b[0].contains_point((5.5,-12))
Out[88]: False
In[89]: b[0].get_xy()
Out[89]:
array([[ 6.89 , -10.00907385],
[ 5.11 , -10.00907385],
[ 5.11 , -14.68307385],
[ 6.89 , -14.68307385],
[ 6.89 , -10.00907385]])
【问题讨论】:
-
你试过points_inside_poly吗?似乎 contains_point 只识别路径本身(docstring)
-
我无法重现此内容。它对我来说是
True。当然需要minimal reproducible example,这样可以排除代码中的任何错误。 -
对我来说,我也得到
True。您使用的是哪个版本的 matplotlib? -
>>> 导入 matplotlib >>> matplotlib.__version__ '2.1.1'
-
我仍然建议您提供minimal reproducible example,即可以复制和粘贴以进行测试的一段代码。否则这都是猜测。
标签: python matplotlib polygon