So i want to change a graph in real time using a slider. I tried learning it this bottom code is from youtube where it worked. When i run it though, all this does is shows a picture of a graph with a slider, that i cant change. I am using spyder IDE if this matters. i tried using: import matplotlib matplotlib.use('tkagg') This opens a new window, but it just craches instantly
import numpy as np
from scipy.interpolate import UnivariateSpline
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
# Initial x and y arrays
x = np.linspace(0, 10, 30)
y = np.sin(0.5*x)*np.sin(x*np.random.randn(30))
# Spline interpolation
spline = UnivariateSpline(x, y, s = 6)
x_spline = np.linspace(0, 10, 1000)
y_spline = spline(x_spline)
# Plotting
fig = plt.figure()
plt.subplots_adjust(bottom=0.25)
ax = fig.subplots()
p = ax.plot(x,y)
p, = ax.plot(x_spline, y_spline, 'g')
# Defining the Slider button
# xposition, yposition, width and height
ax_slide = plt.axes([0.25, 0.1, 0.65, 0.03])
# Properties of the slider
s_factor = Slider(ax_slide, 'Smoothing factor',
0.1, 6, valinit=6, valstep=0.2)
# Updating the plot
def update(val):
current_v = s_factor.val
spline = UnivariateSpline(x, y, s = current_v)
p.set_ydata(spline(x_spline))
#redrawing the figure
fig.canvas.draw()
# Calling the function "update" when the value of the slider is changed
s_factor.on_changed(update)
plt.show()
It looks like you are using matplotlib in inline mode (%matplotlib inline
).
Before your code add this line %matplotlib qt
and run cell. Or just run your code without this command as a .py file with default python - you will get an interactive matplotlib window in which the slider moves (I checked the code in my environment and it works correctly - Python 3.11.3, matplotlib==3.7.1, numpy==1.24.2, scipy==1.10.1)
More about matplotlib magic commands: https://ipython.readthedocs.io/en/stable/interactive/plotting.html