简体   繁体   English

Python-matplotlib:无法使用链接到事件的函数在图形上显示文本

[英]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... 我正在尝试与matplotlib图形进行交互,但某些操作未按计划进行...

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(). 以下是脚本的示例,并在此处描述了应执行的操作:在我的test_figure类的init部分中,我创建了一个图形(图1),添加了子图,绘制了100个随机点,定义了文本框的属性,并将事件“ pick_event”连接到函数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. 使用此函数时,应使用数据的x和y坐标,用它来绘制使用它们的线(在图2中),同时使用文本在图1上显示x和y坐标。

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? 除最后一部分外,几乎所有内容都可以使用:x和y坐标未显示在图1中,我不知道为什么...您有任何想法吗?

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. text (几乎与所有axes类方法一样)会将美工添加到图形中,但不会强制重新渲染。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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