The issue with your grid toggle button not working properly is primarily caused by theblit
parameter.
The Fix:
ani = FuncAnimation(fig, animate, frames=100, interval=50, blit=False)
And make sure your toggle function forces a complete redraw:
def grid_lines(event):
global grid_visible
grid_visible = not grid_visible
if grid_visible:
ax.grid(True, color='white')
else:
ax.grid(False)
# Force immediate redraw
fig.canvas.draw()
Why This Works:
The main issue is that with blit=True
, Matplotlib only redraws the what are returned from the animation function for optimization. Grid lines aren't included in these, so they don't update.
Setting blit=False
forces a complete redraw of the figure with each animation frame.
Using fig.canvas.draw()
instead of fig.canvas.draw_idle()
forces a redraw when the button is clicked.