更新matplotlib中的特定注释

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了更新matplotlib中的特定注释相关的知识,希望对你有一定的参考价值。

我的绘图中的注释很少,只需单击鼠标即可激活。我想更新一个特定的注释。但是,注释会覆盖早期的注释。如何清除旧的特定/特定注释并使用新值更新以使其看起来干净。

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()函数的一部分。这可以通过annotate对象上的Text Class的set_text()方法来完成。 (因为matplotlib.text.Annotation类基于matplotlib.text.Text类)

这是如何做到的:

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中的特定注释的主要内容,如果未能解决你的问题,请参考以下文章

为啥代码片段在 matplotlib 2.0.2 上运行良好,但在 matplotlib 2.1.0 上引发错误

matplotlib的同一注释中的不同字体大小?

Matplotlib 可视化之注释与文本高级应用

使用实时相机预览更新 matplotlib 中的帧

如何找到具有特定注释的所有 Java 对象(不是类)?

正则表达式匹配代码中的特定注释