【问题标题】:Update annotations in Matplotlib using buttons使用按钮更新 Matplotlib 中的注释
【发布时间】:2017-07-15 17:42:54
【问题描述】:

我正在修改 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

【问题讨论】:

    标签: python button matplotlib


    【解决方案1】:

    不幸的是,您要达到的目标并不完全清楚。

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

    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()
    

    【讨论】:

    • 如果这不是您想要的,您需要更新您的问题并具体描述您的目标。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多