Jailbone
Jailbone

Reputation: 177

Update plots through slider (python)

I got a data array looking like data = [[1, 2, 3], [4, 5, 6], [7, 9, 10]....] and x values x_values = np.arange(3).

I want to show the plot of one sub-array at a time and incorporate a slider in my graph whose value should represent the index of the corresponding sub-array. So when I change the slider from for example 1 to 2, it should change from plotting data[1] to plotting data[2] against my x values.

My code looks something like this:

#Initial plot
fig, ax = plt.subplots()
i = 0
plt.subplots_adjust(bottom = 0.15)
ax.plot(x_values, data[i])

#Update function
def update_wave(val):
    i = int(sliderwave.val)

    x_values = np.arange(3)
    ax.cla()
    ax.plot(x_values, data[i))
    fig.canvas.draw_idle()

#Sliders
axwave = plt.axes([0.25, 0.05, 0.5, 0.03])
sliderwave = Slider(axwave, 'Event No.', 0, 100, valinit=0, valfmt='%1.0f')

update_wave(i)
sliderwave.on_changed(update_wave)

It does not work like that. I guess some things don't make sense. Would appreciate some help.

Upvotes: 3

Views: 7207

Answers (1)

panadestein
panadestein

Reputation: 1291

I think you were missing only a small detail in your code, and is that you want the slider to take only discrete values. If this is what you wanted to achieve, then give this code a try:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

# Define data set

DATA = np.random.uniform(1, 10, 300).reshape(-1, 3)
X_VALUES = np.arange(3)

# Initial plot

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.15)
ax.plot(X_VALUES, DATA[0], '-o')

# Update function


def update_wave(val):
    idx = int(sliderwave.val)
    ax.cla()
    ax.plot(X_VALUES, DATA[idx], '-o')
    fig.canvas.draw_idle()


# Sliders

axwave = plt.axes([0.25, 0.05, 0.5, 0.03])

sliderwave = Slider(axwave, 'Event No.', 0, 100, valinit=0, valfmt='%d')
sliderwave.on_changed(update_wave)

plt.show()

In this example I have generated a random data set to plot. Note that in the Slider object I have set the optional argument valfmt='%d', so the slider only take integer values.

Edit

If you want to include a textbox to select the slide number then you will need to add new functions and objects, for example:

def submit(text):
    idx = int(text)
    ax.cla()
    ax.plot(X_VALUES, DATA[idx], '-o')
    fig.canvas.draw_idle()

axtext = plt.axes([0.25, 0.15, 0.5, 0.03])
text_box = TextBox(axtext, 'Slide No.')
text_box.on_submit(submit)

If you want this to work together with the previously defined slider, then you must also modify the shape of the subplots with plt.subplots_adjust(bottom=0.25) for example. The final plot would look like this: enter image description here

Upvotes: 3

Related Questions