python - 使用按钮更新 Matplotlib 中的注释

标签 python button matplotlib

我正在修改 Matplotlib 文档中的按钮示例,以在图中添加文本注释。我的问题是,我无法找到每次按下按钮时更新注释的正确方法,因为注释重叠。我尝试了remove()方法,但不起作用。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

freqs = np.arange(2, 20, 3)

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)
t = np.arange(0.0, 1.0, 0.001)
s = np.sin(2*np.pi*freqs[0]*t)
l, = plt.plot(t, s, lw=2)


class Index(object):
    ind = 0

    def next(self, event):
        self.ind += 1
        i = self.ind % len(freqs)
        ydata = np.sin(2*np.pi*freqs[i]*t)
        l.set_ydata(ydata)
        plt.annotate("lalala", (0, 0))
        plt.draw()

    def prev(self, event):
        self.ind -= 1
        i = self.ind % len(freqs)
        ydata = np.sin(2*np.pi*freqs[i]*t)
        l.set_ydata(ydata)
        plt.annotate("lelele", (0.50, 0))
        plt.draw()

callback = Index()
axprev = plt.axes([0.7, 0.05, 0.1, 0.075])
axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'Next')
bnext.on_clicked(callback.next)
bprev = Button(axprev, 'Previous')
bprev.on_clicked(callback.prev)

plt.show()

如有任何帮助,我们将不胜感激。

源代码:http://matplotlib.org/examples/widgets/buttons.html

最佳答案

不幸的是,您想要实现的目标并不完全清楚。

您当然可以选择更新回调类中的注释:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

freqs = np.arange(2, 20, 3)

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)
t = np.arange(0.0, 1.0, 0.001)
s = np.sin(2*np.pi*freqs[0]*t)
l, = plt.plot(t, s, lw=2)
ann = ax.annotate("", (0, 0))

class Index(object):
    ind = 0

    def next(self, event):
        self.ind += 1
        i = self.ind % len(freqs)
        ydata = np.sin(2*np.pi*freqs[i]*t)
        l.set_ydata(ydata)
        ann.set_text("next clicked")
        ann.set_position((0.6,0.5))
        plt.draw()

    def prev(self, event):
        self.ind -= 1
        i = self.ind % len(freqs)
        ydata = np.sin(2*np.pi*freqs[i]*t)
        l.set_ydata(ydata)
        ann.set_text("previous clicked")
        ann.set_position((0.3,0.5))
        plt.draw()

callback = Index()
axprev = plt.axes([0.7, 0.05, 0.1, 0.075])
axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'Next')
bnext.on_clicked(callback.next)
bprev = Button(axprev, 'Previous')
bprev.on_clicked(callback.prev)

plt.show()

关于python - 使用按钮更新 Matplotlib 中的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42446307/

相关文章:

ios - SwiftUI 中具有双重 Action (点击和长按)的按钮

user-interface - 如何在 JavaFX 场景中定位按钮(或任何 GUI 元素)?

javascript - 在 HTML5 中的图像上创建按钮

python - Python + scipy 中 sigmoid 回归的参数

python - 循环保存图形

python - 如何将自定义注释从数据框添加到堆积条形图?

python - 错误: the label [0] is not in the [index]

python - 如何在没有黑色背景的情况下将 png 图像作为 Sprite 上传到 pygame 中?

python - PIL : How to reopen an image after verifying?

Python virtualenv 很慢