Matplotlib path contains_point

删除回忆录丶 提交于 2021-01-27 18:57:36

问题


I've just discovered the matplotlib path functionality and I'm using it with path.contains_point to check whether points are found within a region defined by 2 bezier curves.

I'm getting some unexpected behaviour where contains_point is returning True when I would have expected it to return False. Specifically, if the point to be tested is to the left of the region then it seems to be incorrect. On the right is ok.

Defining my paths as a number of straight lines rather than curves seems to work as expected.

A failing test case is as follows:

import matplotlib 
import matplotlib.path as mplPath
import matplotlib.patches as patches

import matplotlib.pyplot as plt
import pylab
import pandas as pd

print "MPL Version {}".format(matplotlib.__version__) #1.5.0
print "MPL NP Version {}".format(matplotlib.__version__numpy__) #1.6

path_data = [
    (mplPath.Path.MOVETO, (2, 10)),
    (mplPath.Path.CURVE4, (0, 100)),
    (mplPath.Path.CURVE4, (20, 100)),
    (mplPath.Path.CURVE4, (40, 150)),
    (mplPath.Path.MOVETO, (40, 150)),
    (mplPath.Path.CURVE4, (42, 45)),
    (mplPath.Path.CURVE4, (20, 30)),
    (mplPath.Path.CURVE4, (2, 10))
    ]

codes, verts = zip(*path_data)
path = mplPath.Path(verts, codes)
patch = patches.PathPatch(path, facecolor='r', alpha=0.5)

#Plot the patch and a some of the test points to visualise
fig = plt.figure()
ax = fig.add_subplot(111)
ax.add_patch(patch)
ax.set_xlim(0, 50)
ax.set_ylim(0, 200)

ax.scatter(1, 50)
ax.scatter(20, 120)
ax.scatter(20, 25)
print path.contains_point((1,50)) #This should be false but is actually true
print path.contains_point((20,120)) #This should be false but is actually true
print path.contains_point((20, 25)) #This should be false and it is

plt.show()

Thanks in advance for any help you can provide. Python version is 2.7, Anaconda Distro on Linux Mint 17.3

Jim


回答1:


You have an open path (extra moveto command). Once you comment it out, it works fine.

path_data = [
    (mplPath.Path.MOVETO, (2, 10)),
    (mplPath.Path.CURVE4, (0, 100)),
    (mplPath.Path.CURVE4, (20, 100)),
    (mplPath.Path.CURVE4, (40, 150)),
  #  (mplPath.Path.MOVETO, (40, 150)),
    (mplPath.Path.CURVE4, (42, 45)),
    (mplPath.Path.CURVE4, (20, 30)),
    (mplPath.Path.CURVE4, (2, 10))
    ]


来源:https://stackoverflow.com/questions/36730261/matplotlib-path-contains-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!