matplotlib中的可拖动图例,同时具有事件选择功能

时间:2017-12-15 13:08:48

标签: python matplotlib tkinter

我已经在图例上创建了事件选择,但我在同时实现可拖动的图例时遇到了困难。这两个似乎有冲突,因为可移动的图例在删除实现事件选择的这一行时确实有效:self.canvas.mpl_connect('pick_event', self.onpick)

import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np

import tkinter as tk

class App:
    def __init__(self,master):
        self.master = master

        aveCR = {0:np.array([.582,1.081,1.507,1.872,2.180]),1:np.array([2.876,6.731,1.132,1.305,1.217])}    
        legend = ['A', 'AB']

        plotFrame = tk.Frame(master)
        plotFrame.pack()

        f = plt.Figure()
        self.ax = f.add_subplot(111)
        self.canvas = FigureCanvasTkAgg(f,master=plotFrame)
        self.canvas.show()
        self.canvas.get_tk_widget().pack()
        self.canvas.mpl_connect('pick_event', self.onpick)

        # Plot
        lines = [0] * len(aveCR)
        for i in range(len(aveCR)):        
            X = range(len(aveCR[i]))
            lines[i], = self.ax.plot(X,aveCR[i],label=legend[i])

        # Legend
        leg = self.ax.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=2, borderaxespad=0.)
        if leg:
            leg.draggable()

        self.lined = dict()
        for legline, origline in zip(leg.get_lines(), lines):
            legline.set_picker(5)  # 5 pts tolerance
            self.lined[legline] = origline

    def onpick(self, event):
        # on the pick event, find the orig line corresponding to the
        # legend proxy line, and toggle the visibility
        legline = event.artist
        origline = self.lined[legline]
        vis = not origline.get_visible()
        origline.set_visible(vis)
        # Change the alpha on the line in the legend so we can see what lines
        # have been toggled
        if vis:
            legline.set_alpha(1.0)
        else:
            legline.set_alpha(0.2)
        self.canvas.draw()

root = tk.Tk()
root.title("hem")
app = App(root)
root.mainloop()

1 个答案:

答案 0 :(得分:0)

因为你使用了一个可拖动的图例,所以当然有可能在图例上出现一个pick_event;事实上,在图例中的一条线上发生的所有pick_event也发生在图例中。

现在,如果选择的艺术家是字典中的一行,您可能希望仅进行自定义选择。您可以通过查询event.artist是否在self.lined字典中来检查是否发生这种情况。

    def onpick(self, event):
        if event.artist in self.lined.keys():
            legline = event.artist
            origline = self.lined[legline]
            vis = not origline.get_visible()
            origline.set_visible(vis)
            # Change the alpha on the line in the legend so we can see what lines
            # have been toggled
            if vis:
                legline.set_alpha(1.0)
            else:
                legline.set_alpha(0.2)
            self.canvas.draw_idle()