Python Matplotlib散点图:打开与我单击的点对应的图像
我制作了一个简单的matplotlib代码,在这里我生成了散点图。现在,当我点击该点时,我想打开对应于该点的图像。例如,当我点击第一点时,它应该打开图像一,对于第二点,它应该打开图像二。这是我的密码Python Matplotlib散点图:打开与我单击的点对应的图像,python,matplotlib,Python,Matplotlib,我制作了一个简单的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
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()
将matplotlib.image导入为mpimg
将numpy作为np导入
将matplotlib.pyplot作为plt导入
x=[1,2,3,4]
y=[1,4,9,16]
图=plt.图()
ax=图添加_子批次(111)
ax.图(x,y,'o')
coords=[]
def onclick(事件):
全球ix,iy
ix,iy=event.xdata,event.ydata
打印“x=%f,y=%f%”(ix,iy)
全球协调
坐标附加((ix,iy))
打印透镜(coords)
z=len(coords)-1
打印坐标[z][1]
per=(10*coords[z][1])/100
errp=abs(坐标[z][1]+每小时)
errn=abs(坐标[z][1]-per)
打印“errn=%f,errp=%f”%(errn,errp)
对于范围内的i(len(x)):
如果abs(float(y[i])>=errn和abs(float(y[i]))如果您希望在缩放时使用此功能,我将使发生单击的距离成为轴限制的函数:
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()
将matplotlib.image导入为mpimg
将numpy作为np导入
将matplotlib.pyplot作为plt导入
plt.close(“全部”)
x=[1,2,3,4]
y=[1,4,9,16]
图=plt.图()
ax=图添加_子批次(111)
ax.图(x,y,'o')
def onclick(事件):
ix,iy=event.xdata,event.ydata
打印(“我在x={0:5.2f},y={1:5.2f}处单击了”。格式(ix,iy))
#根据轴范围计算合理的距离
#从必须发生点击的实际点算起(在本例中为5%)
ax=plt.gca()
dx=0.05*(ax.get\u xlim()[1]-ax.get\u xlim()[0])
dy=0.05*(ax.get_ylim()[1]-ax.get_ylim()[0])
#如果单击足够近,请检查每个点:
对于范围内的i(len(x)):
如果(x[i]>ix-dx和x[i]iy-dy和y[i]
Hi Bart感谢您的解决方案,这非常有效。如有必要,我将在这里添加工作解决方案。