'Matplotlib how to navigate through graphs by clicking a next button
Let's assume I have a couple of datasets (numpy arrays, or similar) and I want to plot them with matplotlib. Not all at once but after each other. I want to navigate by clicking with the mouse on a "next" button. I post my solution. Is there an alternative or improvements? It works for me but somehow it took me quite a bit to figure it out. Maybe it helps others.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Button
x = np.arange(0, 4*np.pi, 0.1) # start,stop,step
y_sin = np.sin(x)
y_sin2 = np.sin(x + np.pi/4)
y_cos = np.cos(x)
data = [y_sin, y_sin2, y_cos]
data_index = 0
data_len = len(data)
# create figure
fig, ax = plt.subplots()
line, = plt.plot(x, data[data_index], lw=2)
ax.set_xlabel('Time [s]')
# adjust the main plot
plt.subplots_adjust(left=0.25, bottom=0.25)
# function called anytime the button is pressed
def update(val):
line.set_ydata(data[val])
fig.canvas.draw_idle()
# create `matplotlib.widgets.Button`
nextax = plt.axes([0.8, 0.025, 0.1, 0.04]) # position of button
button_next = Button(nextax, 'next', hovercolor='0.975')
prevax = plt.axes([0.3, 0.025, 0.1, 0.04]) # position of button
button_prev = Button(prevax, 'prev', hovercolor='0.975')
def next(event):
print("function NEXT: ## " + str(event))
global data_index
global data_len
data_index = (data_index + 1) % data_len
update(data_index)
def prev(event):
print("function PREV: ## " + str(event))
global data_index
global data_len
data_index = (data_index - 1) % data_len
update(data_index)
button_prev.on_clicked(prev)
button_next.on_clicked(next)
plt.show()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
