2016-05-30 46 views
0

我做了一個簡單的matplotlib代碼,我在哪裏生成scatterplot。現在我想打開對應點的圖像,當我點擊該點時。例如,當我點擊第一點時,它應該打開圖像一,對於第二點它應該打開圖像二。這裏是我的代碼,Matplotlib scatterplot:打開圖像對應的點,我點擊

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

回答

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() 
+0

嗨巴特感謝您的解決方案,這是偉大的工作。如有需要,我會在此添加工作解決方案。 – dking