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

2024-06-16 13:53:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在图例上创建了事件拾取,但是我很难同时实现一个可拖动的图例。当删除实现事件选取的这一行时,这两个似乎是冲突的,因为可拖动的图例确实起作用: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()

Tags: theimportselfmastereventroottkcanvas
1条回答
网友
1楼 · 发布于 2024-06-16 13:53:46

因为您使用的是可拖动的图例,所以当然有可能在图例上发生pick\u事件;事实上,在图例中的一行上发生的所有pick\u事件也会在图例中发生。你知道吗

现在,您只希望在选定的艺术家是字典中的一行时进行自定义拾取。您可以通过查询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()

相关问题 更多 >