How to refresh text in Matplotlib?

前端 未结 1 1030
慢半拍i
慢半拍i 2021-02-19 10:26

I wrote this code to read data from an excel file and to plot them. For a certain x-value, I desire to know the y-values of all the lines so I create a slider to change this x-v

相关标签:
1条回答
  • 2021-02-19 10:46

    With matplotlib widgets, the update method works best if you create an artist object and adjust its value (like you do with line in your code). For a text object, you can use the set_text and set_position method to change what it displays and where. As an example,

    import numpy as np
    import pylab as plt
    from matplotlib.widgets import Slider
    
    fig, ax = plt.subplots()
    plt.subplots_adjust(bottom=0.25)
    sax = plt.axes([0.25, 0.1, 0.65, 0.03])
    
    x = np.linspace(0,2.*np.pi,100)
    f = np.sin(x)
    l, = ax.plot(x, f)
    
    slider1 = Slider(sax, 'amplitude', -0.8, 0.8, valinit=0.8)
    
    tpos = int(0.25*x.shape[0])
    t1 = ax.text(x[tpos], f[tpos],  str(slider1.val))
    
    tpos = int(0.75*x.shape[0])
    t2 = ax.text(x[tpos], f[tpos],  str(slider1.val))
    
    def update(val):
        f = slider1.val*np.sin(x)
        l.set_ydata(f)
    
        # update the value of the Text object
        tpos = int(0.25*x.shape[0])
        t1.set_position((x[tpos], f[tpos]))
        t1.set_text(str(slider1.val))
    
        tpos = int(0.75*x.shape[0])
        t2.set_position((x[tpos], f[tpos]))
        t2.set_text(str(slider1.val))
    
        plt.draw()
    
    slider1.on_changed(update)
    plt.show()
    

    which looks like,

    The alternative may be to clear and redraw the text each time but this is slower and will be more hassle.

    0 讨论(0)
提交回复
热议问题