当单击pcolormesh正方形的中心时,使用matplotlib pick事件触发吗? [英] Use matplotlib pick event to trigger when center of pcolormesh squares are clicked?

查看:107
本文介绍了当单击pcolormesh正方形的中心时,使用matplotlib pick事件触发吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个更广泛的项目,但是在使用带有pcolormesh的matplotlibs picker=Truepick_event时遇到了问题.它起作用,但不直观,因为仅当我沿热图框"的边缘单击时才触发选择事件,它会返回周围的索引(因此,如果单击角,则4的交集会返回4的索引框).

I am working on a broader project, but am running into an issue using matplotlibs picker=True and pick_event with a pcolormesh. It works, but is not intuitive as the pick event is only triggered when i click along the edges of the heatmap 'boxes', and it returns the surrounding indices (so if you click a corner 4 indices are returned by the intersection of the 4 boxes at that point).

例如,在下图中,当我单击黄色圆圈附近时,我的选择器将返回索引[5 8](5是下面的框,上面的8是框).相反,当单击该框"时,我只想返回索引5.

For example, in the following picture when I click near the yellow circle my picker returns indices [5 8] (5 is the box below and 8 above). Instead, I'd like to return only index 5 when that 'box' is clicked.

这是我用来说明问题的代码:

Here is the code I used to exemplify my issue:

import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
#import matplotlib.animation as animation
#from matplotlib import style
import numpy as np

import Tkinter as tk
import ttk

def customplot(f,X):
    try:
        f.clf()
    except:
        None
    try:
        ax=ax
    except:
        ax=f.add_subplot(111)
    ax.pcolormesh(X,picker=True)
    ax.set_yticks(arange(0.5,len(X)+0.5))
    ax.set_xticks(arange(0.5,len(X)+0.5))
    ax.set_yticklabels(["LabY"+str(l) for l in range(len(X))])
    ax.set_xticklabels(["LabX"+str(l) for l in range(len(X))])

class My_GUI:

    def __init__(self,master):
        self.master=master
        self.f = Figure(figsize=(5,5), dpi=100)
        self.canvas1=FigureCanvasTkAgg(self.f,self.master)
        self.canvas1.get_tk_widget().pack(side="top",fill='x',expand=True)
        self.canvas1.mpl_connect('pick_event',self.onpick)
        self.toolbar=NavigationToolbar2TkAgg(self.canvas1,master)
        self.toolbar.update()
        self.toolbar.pack(side='top',fill='x')           
        self.drawcustomplot()

    def drawcustomplot(self):
        self.X=array(np.random.normal(size=[3,3]))
        customplot(self.f,self.X)
        #plt.xticks([1,2,3],['one','two','three'])
        self.canvas1.show()

    def onpick(self,event):
        print('Returned indices')
        print(event.ind)
        print('mapping back:')
        self.myxlabels=["LabX"+str(l) for l in range(len(self.X))]
        self.myylabels=["LabY"+str(l) for l in range(len(self.X))]
        self.ypos=event.ind[0] / 3
        self.xpos=event.ind[0] % 3
        print("Y: "+str(self.myylabels[self.ypos])+'  X:'+str(self.myxlabels[self.xpos]))


root=tk.Tk()
gui=My_GUI(root)
root.mainloop()

这是对这里发现的问题的进一步解答:

this is further to the question found here: Can matplotlib pick_event return array indeces rather than values or pixels?. I'd like to avoid trying to draw an underlying scatterplot that is masked by the pcolormesh, but handles the picker events if possible as I feel there must be a simpler way to achieve the desired result.

推荐答案

我建议在这里使用button_press_event.由此,您可以轻松获得单击像素的坐标.如果是imshow图,则更容易

I would suggest to use a button_press_event here. From that you can easily obtain the coordinates of the clicked pixel. In the case of an imshow plot it's even easier,

x = int(np.round(event.xdata))
y = int(np.round(event.ydata))

完整示例(使用imshow):

import numpy as np
import matplotlib.pyplot as plt

X=np.array(np.random.normal(size=[3,3]))

myxlabels=["LabX"+str(l) for l in range(len(X[0,:]))]
myylabels=["LabY"+str(l) for l in range(len(X))]
plt.imshow(X)
plt.xticks(range(len(X[0,:])),myxlabels )
plt.yticks(range(len(X)),myylabels )

def onclick(event):
    print('Returned indices')
    print(event.xdata, event.ydata)
    print('mapping back:')
    x = int(np.round(event.xdata))
    y = int(np.round(event.ydata))
    tx = "Y: {}, X: {}, Value: {:.2f}".format(myylabels[y], myxlabels[x], X[y,x])
    print(tx)

plt.gcf().canvas.mpl_connect('button_press_event', onclick)

plt.show()

这篇关于当单击pcolormesh正方形的中心时,使用matplotlib pick事件触发吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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