我制作了一个简单的matplotlib代码,我正在生成散点图。现在我想打开对应于点击该点时的点的图像。例如,当我点击第一点时它应该打开图像一,对于第二点它应该打开图像二。这是我的代码,
import matplotlib.image as mpimg
import numpy as np
import matplotlib.pyplot as plt
x=[1,2,3,4]
y=[1,4,9,16]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y,'o')
coords = []
def onclick(event):
global ix, iy
ix, iy = event.xdata, event.ydata
print 'x = %f, y = %f'%(ix, iy)
global coords
coords.append((ix, iy))
print len(coords)
z=len(coords)-1
print coords[z][1]
per = (10*coords[z][1])/100
errp = abs(coords[z][1]+per)
errn = abs(coords[z][1]-per)
print "errn=%f, errp=%f"%(errn, errp)
for i in range(len(x)):
if abs(float(y[i])) >= errn and abs(float(y[i])) <= errp :
print y[i]
fig2 = plt.figure()
img=mpimg.imread('white.png')
line2 = plt.imshow(img)
fig2.show()
return coords
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
现在的问题是当我放大y值非常高的情节时(即使我点击远离该点,也会打开10 ^ 3的数量。
点击点本身而不是附近区域的某个地方时,如何获得所需图像?
[如果这是重复的问题,请给我一个原始问题的链接]
编辑:忘记添加图片white.png
答案 0 :(得分:1)
如果你想在缩放时使用它,我会使点击必须发生的距离是轴限制的函数:
import matplotlib.image as mpimg
import numpy as np
import matplotlib.pyplot as plt
plt.close('all')
x=[1,2,3,4]
y=[1,4,9,16]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, 'o')
def onclick(event):
ix, iy = event.xdata, event.ydata
print("I clicked at x={0:5.2f}, y={1:5.2f}".format(ix,iy))
# Calculate, based on the axis extent, a reasonable distance
# from the actual point in which the click has to occur (in this case 5%)
ax = plt.gca()
dx = 0.05 * (ax.get_xlim()[1] - ax.get_xlim()[0])
dy = 0.05 * (ax.get_ylim()[1] - ax.get_ylim()[0])
# Check for every point if the click was close enough:
for i in range(len(x)):
if(x[i] > ix-dx and x[i] < ix+dx and y[i] > iy-dy and y[i] < iy+dy):
print("You clicked close enough!")
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()