鼠标单击后将文本添加到matplotlib图

时间:2019-12-19 16:38:28

标签: python pandas matplotlib tkinter

下面的代码创建一个pandas数据框,然后按散点图绘制数据。为了在大型应用程序中有意义,我需要将其发布到tkinter框架,因此我已经在MRE中进行了所有模拟。我挂断电话的地方是希望用户单击数据点之一时弹出一个文本框。在下面的代码中,mpl_connect确实调用了show_text函数,因为print(idx)有效。但是,我创建ax.text的行似乎没有任何作用。

我在做什么错了?

import pandas as pd
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from tkinter import *

class TestClass(Frame):
    def __init__(self, parent=None):
        self.parent = parent
        Frame.__init__(self)
        self.df = pd.DataFrame(np.random.randn(10, 2), columns=['A','B'])
        self.show_chart()

    def show_chart(self):
        g_top = Toplevel(bg='white')
        g_top.title('Spread/Leverage chart')
        x = self.parent.winfo_x()
        y = self.parent.winfo_y()
        w = self.parent.winfo_screenwidth() * 0.4
        h = self.parent.winfo_screenheight() * 0.6
        g_top.geometry('%dx%d+%d+%d' % (w, h, x, y))

        can = Canvas(g_top, bg='white')
        can.pack(side='left', fill='both', expand=True)

        frm = Frame(can, bg='white')
        can.create_window((4,4), window=frm, anchor='nw')

        fig = Figure(figsize=(6,6), dpi=100)
        fig.set_facecolor('white')
        ax = fig.gca()
        chart_type = FigureCanvasTkAgg(fig, frm)
        chart_type.get_tk_widget().grid(column=0, row=0)
        self.df.plot(kind='scatter', ax=ax, x='A', y='B',
                    picker=True)

        #Create annotation
        fig.canvas.mpl_connect('pick_event', lambda event, ax=ax: self.show_text(event, ax))

    def show_text(self, event, ax):
        #Add text to chart
        idx = event.ind
        print(idx)
        ax.text(0.05, 0.95, 'Ind' + str(idx), transform=ax.transAxes, verticalalignment='top')

if __name__ == '__main__':
    root=Tk()
    ui = TestClass(root)
    ui.pack()
    root.mainloop()

0 个答案:

没有答案