I want to write a code where the animation function in matplotlib starts plotting only after the matplotlib button widget is clicked by me. Here are my steps:
- I create a empty plot.
- I press my mouse anywhere on the plot which activates click events and the x and y coordinates are stored in a list.
- I click on press button which runs the animation function.
- The animation function plots by using the stored x and y coordinates.
I got successful in the storing the x and y coordinates but the press button doesn't give me the animated plot that I need. This is the first error I am facing.
The second error is my click event also stores the coordinates of where I press the button. I don't want coordinates during button press. I just the coordinates on the empty plot.
from matplotlib.widgets import Button
from matplotlib.animation import FuncAnimation
x_coord,y_coord = [],[]
fig = plt.figure()
axis = fig.add_subplot(111,xlim=(-5,15),ylim=(-5,15))
line, = axis.plot([],[],lw=3)
def init():
line.set_data([],[])
return line,
def animate(i):
x_points = [0,x_coord[i]]
y_points = [0,y_coord[i]]
line.set_data(x_points,y_points)
return line,
def onclick(event):
print(event.xdata,event.ydata)
x_coord.append(event.xdata)
y_coord.append(event.ydata)
def buttonPress(pressevent):
print('pressed')
print(x_coord)
ani = FuncAnimation(fig,animate,init_func=init,frames=len(x_coord),interval=100,blit=False)
cid = fig.canvas.mpl_connect('button_press_event',onclick)
axprev = plt.axes([0.5,0,0.1,0.1])
button = Button(axprev,'press')
button.on_clicked(buttonPress)
plt.show()```