【问题标题】:Matplotlib scatterplot : Open image corresponding to point which i clickMatplotlib scatterplot:打开与我单击的点对应的图像
【发布时间】:2016-05-30 05:05:40
【问题描述】:

我制作了一个简单的 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

【问题讨论】:

    标签: python matplotlib


    【解决方案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()
    

    【讨论】:

    • 嗨,巴特感谢您的解决方案,这很好用。如有必要,我将在此处添加工作解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 2015-09-09
    • 2019-04-23
    • 1970-01-01
    相关资源
    最近更新 更多