Search code examples
pythonclickpause

Make the program pause by button or mouse click in python package matplotlib


Through the program interface button or mouse click to make the program pause, click the button or mouse again to allow the program to continue from the place where it was last stopped, the focus is to pause how to achieve.The time from the last pause again is uncertain.My codes are following:

import matplotlib.pyplot as plt
class ab():
    def __init__(self,x,y):
        self.x=x
        self.y=y
a=ab(2,4)
b=ab(2,6)
c=ab(2,8)
d=ab(6,10)
f=ab(6,13)
e=ab(6,15)
task=[]
task.append(a)
task.append(b)
task.append(c)
task.append(d)
task.append(e)
task.append(f)
for i in task:
    while i.x<=30:
        print(i.x)
        plt.plot(i.x,i.y,'o')
        plt.pause(0.1)
        i.x=i.x+2
        i.y=i.y+2

plt.show()

Solution

  • You can combine matplotlib's animation module with matplotlib's event connections. The code below should do more or less what you want:

    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
    
    # I'm replacing your class with two lists for simplicity
    x = [2,2,2,6,6,6]
    y = [4,6,8,10,13,15]
    
    # Set up the figure
    fig, ax = plt.subplots()
    point, = ax.plot(x[0],y[0],'o')
    
    # Make sure all your points will be shown on the axes
    ax.set_xlim(0,15)
    ax.set_ylim(0,15)
    
    # This function will be used to modify the position of your point
    def update(i):
        point.set_xdata(x[i])
        point.set_ydata(y[i])
        return point
    
    # This function will toggle pause on mouse click events
    def on_click(event):
        if anim.running:
            anim.event_source.stop()
        else:
            anim.event_source.start()
        anim.running ^= True
    
    npoints = len(x)
    
    # This creates the animation
    anim = FuncAnimation(fig, update, npoints, interval=100)
    anim.running=True
    
    # Here we tell matplotlib to call on_click if the mouse is pressed
    cid = fig.canvas.mpl_connect('button_press_event', on_click)
    
    # Finally, show the figure
    plt.show()