更新 matplotlib 中的特定注释 [英] Update a specific annotation in matplotlib

查看:44
本文介绍了更新 matplotlib 中的特定注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的图中几乎没有注释可以通过单击鼠标激活.我想更新一个特定的注释.但是,注释会覆盖较早的注释.如何清除旧的特定/特定注释并使用新值更新以使其看起来干净.

I have few annotations in my plot which are activated with mouse click. I want to update one specific annotation. However, the annotation is overriding the earlier annotation. How do I clear the old specific/particular annotation and update with new value so that it looks clean.

from matplotlib import pyplot as plt

fig, ax = plt.subplots()
x=1

def annotate():
    global x    
    if x==1:        
        x=-1
    else:
        x=1
    ax.annotate(x, (0.5,0.5), textcoords='data', size=10)
    ax.annotate('Other annotation', (0.5,0.4), textcoords='data', size=10)

def onclick(event):     
    annotate()
    fig.canvas.draw()

cid = fig.canvas.mpl_connect('button_press_event',onclick)

推荐答案

您可以先创建注释对象,然后将文本作为 annotate() 函数的一部分进行更新.这可以通过 Text Class 的 set_text() 方法来完成在注释对象上.(因为 matplotlib.text.Annotation 类是基于 matplotlib.text.Text 类的)

You can create the annotation objects before and then update the text as part of your annotate() function. This can be done by set_text() method of Text Class on the annotate object. (because matplotlib.text.Annotation class is based on matplotlib.text.Text class)

这是如何做到的:

from matplotlib import pyplot as plt

fig, ax = plt.subplots()
x=1
annotation = ax.annotate('', (0.5,0.5), textcoords='data', size=10) # empty annotate object
other_annotation = ax.annotate('Other annotation', (0.5,0.4), textcoords='data', size=10) # other annotate

def annotate():
    global x
    if x==1:
        x=-1
    else:
        x=1
    annotation.set_text(x)


def onclick(event):
    annotate()
    fig.canvas.draw()

cid = fig.canvas.mpl_connect('button_press_event',onclick)
plt.show()

这篇关于更新 matplotlib 中的特定注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆