简体   繁体   中英

Python-matplotlib: Can't display text on figure using a function linked to an event

I'm trying to interact with a matplotlib figure but something doesn't go as planned...

Below is the sample of the script and here the description of what it should do : in the init part of my test_figure class, I create a figure (figure 1), add a subplot, plot 100 random points, define properties for a textbox and connect the event 'pick_event' to the function onpick(). This function should, when used take x and y coordinates of data, use it to plot a line using them (in figure 2) and at the same time display x and y coordinates on figure 1 using text.

Almost all of it works, except for the last part: the x and y coordinates are not displayed on figure 1 and I can't figure out why... do you have any ideas?

Thanks!

import numpy as np
import matplotlib.pyplot as plt

class test_figure:

    def __init__(self):
        self.fig = plt.figure(1)
        self.ax = self.fig.add_subplot(111)
        self.ax.set_title('Click on data')
        # 3 pixels around point
        line, = self.ax.plot(np.random.rand(100), 'o', picker=3) 
        self.fig.canvas.mpl_connect('pick_event', self.onpick)

    def onpick(self, event):
        thisline = event.artist
        xdata = thisline.get_xdata()
        ydata = thisline.get_ydata()
        ind = event.ind
        self.fig2 = plt.figure(2)
        self.ax2 = self.fig2.add_subplot(111)
        line, = self.ax2.plot(xdata[ind]*range(60)+ydata[ind])
        self.fig.text(0.5,0.5,'pouet :'+str(xdata[ind]))

a = test_figure()

add

self.fig.canvas.draw()

to the end of you callback. text (like almost all axes class methods) adds the artist to the figure, but does not force a re-rendering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM