How can I incorporate a slider into my plot to manipulate a variable? How can I incorporate a slider into my plot to manipulate a variable? tkinter tkinter

How can I incorporate a slider into my plot to manipulate a variable?


Following matplotlib slider for parameters, it's possible to use the matplotlib.widgets.Slider module to update the data contained in the figure.

Simply define your function that you're plotting with some arbitrary parameter, make a slider and stuff it into your plot, and call fig.set_data with your function evaluated at the new slider value everytime the slider changes. This is done by defining an update function (see below) and calling Slider.on_changed(my_update_function).

import numpy as npimport matplotlib.pyplot as pltimport matplotlib.cm as cm      from matplotlib.widgets import Slidervals = np.linspace(-np.pi,np.pi,100)xgrid, ygrid = np.meshgrid(vals,vals)       def f(x, y, b):    return np.sin(x * b)b = 5ax = plt.subplot(111)plt.subplots_adjust(left=0.15, bottom=0.25)fig = plt.imshow(f(xgrid, ygrid, b), cm.gray)plt.axis('off')fig.axes.get_xaxis().set_visible(False)fig.axes.get_yaxis().set_visible(False)axb = plt.axes([0.15, 0.1, 0.65, 0.03])sb = Slider(axb, 'b', 0.1, 10.0, valinit=b)def update(val):    fig.set_data(f(xgrid, ygrid, val))sb.on_changed(update)plt.show()

This should produce the plot you're looking for, where you scan over b.