arpan
arpan

Reputation: 139

Get slider value in back end as python

I am plotting a graph using matplotlib in python using Jupyter and I want to make a slider below the graph,I mean parallel to X-axis (in same plot) which take the slider value in python code and update the graph on the basis of slider value.

Please help me. Thanks in advance.

Upvotes: 0

Views: 545

Answers (1)

sergio verduzco
sergio verduzco

Reputation: 351

One way to do this is by using the Jupyter Widgets extension. This includes the interact function.

Using pip you can install this as:

pip install ipywidgets  
jupyter nbextension enable --py --sys-prefix widgetsnbextension

Then you can create a plot, a function that updates that plot, and pass both as arguments to interact.

Here's a Jupyter cell that does it:

import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact

# Create some data to visualize
data_samples = 100
data_length = 500
data = np.zeros((data_samples, data_length))
for i in range(data_samples):
    data[i,:] = np.random.normal(0., 1+0.1*i, data_length)

# Define a function to update the plot
def update_plot(frame):
    binz, valz = np.histogram(data[frame,:], range=(-10.,10), bins=50)
    for count, patch in zip(binz, patches):
        patch.set_height(count)
    return 

% matplotlib qt5
hist, bins, patches = plt.hist(data[0,:], range=(-10.,10), bins=50)
widget = interact(update_plot, frame=(0, data_samples-1))
plt.show()

Caveat: I tested this with Python 3.5 and the qt5 backend.

Upvotes: 3

Related Questions