Interactive Plots

Hi I got stuck in one of my ML-related projects. I wanted to use interactive diagrams, but my plots are not interactive. (I tried to run it in both Google Colab and Jupyter notebook(browser) )

this is my code:

import numpy as np

import matplotlib.pyplot as plt

from matplotlib.widgets import Slider

Sample data

X = np.arange(10)

y = 2 * X + np.random.normal(0, 1, 10)

Linear regression model

def linear_regression_line(slope, intercept):

return slope * X + intercept

Initial plot

fig, ax = plt.subplots()


ax.scatter(X, y, label=‘Data points’)

[line] = ax.plot(X, linear_regression_line(2, 0), ‘r-’, label=‘Regression line’)




Slider for slope and intercept

ax_slope = plt.axes([0.25, 0.1, 0.65, 0.03])

ax_intercept = plt.axes([0.25, 0.15, 0.65, 0.03])

slope_slider = Slider(ax_slope, ‘Slope’, 0.0, 4.0, valinit=2.0)

intercept_slider = Slider(ax_intercept, ‘Intercept’, -10.0, 10.0, valinit=0.0)

Update function for the slider

def update(val):

line.set_ydata(linear_regression_line(slope_slider.val, intercept_slider.val))





this plot is generated, but the sliders should’ve been interactive. Can you please help me with this?

1 Like

The matplotlib.widgets might not work as expected in cloud environments. Can you try running it locally and seeing if that works?

Thanks! Will look into it!

I run the code in VS code. Still, I am getting the same result. no movement in the image slider…

Hey again, sorry for the late reply.

I was able to make it work by running the code in a VSCode Jupyter Notebook by changing the backend of the notebook with the command

%matplotlib widget

So, make a code block above the imports that just has that line – it might ask you to download some additional packages. And then your code below that, then it should render it correctly.

Let me know if there are any issues. You might be able to run it on a Cloud environment, but I have not tested it yet.

Yeah it worked. Thanks a lot!

1 Like