matplotlib pick_event 可以返回数组 indeces 而不是值或像素吗? [英] Can matplotlib pick_event return array indeces rather than values or pixels?

查看:46
本文介绍了matplotlib pick_event 可以返回数组 indeces 而不是值或像素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为matplotlib中的情节编写点选择器.我希望它告诉我我单击的绘制数组的 i、j 索引.似乎唯一的选项是 event.mouseevent.xdata,它是根据绘制的坐标值,或 event.mouseevent.x,这是根据像素(从我所看到的像素"不是与网格框相同,即我要查找的内容.

I'm trying to write a point picker for a plot in matplotlib. I'd like it to tell me the i, j indeces of the plotted array where I have clicked. It seems that the only options are for event.mouseevent.xdata, which is in terms of the plotted coordinate values, or event.mouseevent.x, which is in terms of pixels (from what I can see "pixels" isn't the same as grid boxes i.e. what I'm looking for).

我是否误解了 xdata/x 是什么.有没有办法做我想做的事.

Have I misunderstood what xdata/x are. Is there a way to do what I want.

谢谢尼尔

被点击的图像是一个二维数组图,例如 pcolormesh

the image being clicked on is a 2D array plot, for instance with pcolormesh

推荐答案

您可以:

  • 首先要使您的艺术家(以下示例中的数组)可以选择.
  • 在点击操作上,检查点击是否在艺术家身上
  • 使用 event.ind [0] 属性获取索引.
  • first make your artist (the array in the example below) pickable.
  • on click action, check that the click is on the artist
  • use the event.ind[0] property to get the index.

其他文档此处.示例如下:

from numpy import linspace
from numpy import cos
from numpy import pi
import matplotlib.pyplot as plt

x = linspace(0,1,100)
y = cos(x*8*pi)   # your array

fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot(x, y, 'b',picker=10)

def onpick(event):

    if event.artist!=line:  #check that you clicked on the object you wanted
        return True     
    if not len(event.ind):  #check the index is valid
        return True
    ind = event.ind[0]

    ax.plot(x[ind],y[ind],'ro')

    fig.canvas.draw() 
    return True

fig.canvas.mpl_connect('pick_event', onpick)
fig.show()

好的.然后,您可以先在网格点上精确绘制一条线,然后在上方绘制pcolormesh对象,然后隐藏该线.这是代码

Ok. Then you can first plot a line exactly at your grid points, then draw your pcolormesh object above, and hide the line. Here's the code

x = linspace(0,9,10)+.5
y = linspace(0,9,10)+.5   # your array
x,y=meshgrid(x,y)
x=x.flatten()
y=y.flatten()

fig = plt.figure()
ax = fig.add_subplot(111)

line, = ax.plot(x, y, 'b',picker=10)
line.set_visible(False)
ax.pcolormesh(np.random.randn(10,10))

def onpick(event):

    if event.artist!=line:  #check that you clicked on the object you wanted
        return True     
    if not len(event.ind):  #check the index is valid
        return True
    ind = event.ind[0]

    ax.plot(x[ind],y[ind],'ro')

    fig.canvas.draw() 
    return True

fig.canvas.mpl_connect('pick_event', onpick)
fig.show()

这篇关于matplotlib pick_event 可以返回数组 indeces 而不是值或像素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆