更新matplotlib中的特定注释 [英] Update a specific annotation in 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()函数的一部分进行更新.可以通过文本类的 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屋!