Matplotlib - Slider Widget

Matplotlib - Slider Widget

Matplotlib offers a Slider widget in its widgets module, which can be useful for interactively visualizing data by allowing users to control various parameters of a plot.

Below, we'll guide you through creating a simple sine wave where you can adjust its frequency using a slider:

  • Import necessary modules:
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider 
  • Create the initial plot:
# Initial data x = np.linspace(0, 4 * np.pi, 1000) freq = 1.0 y = np.sin(freq * x) fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.25) # leave space at the bottom for the slider l, = ax.plot(x, y) ax.set_title("Sine Wave - Adjust Frequency using Slider") 
  • Add the slider:
# Define an axes area for the slider ax_slider = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor='lightgoldenrodyellow') slider = Slider(ax_slider, 'Freq', 0.1, 5.0, valinit=freq) 
  • Update function for the slider:
def update(val): freq = slider.val y_new = np.sin(freq * x) l.set_ydata(y_new) fig.canvas.draw_idle() # Attach the update function to the slider's "changed" event slider.on_changed(update) 
  • Display the plot:
plt.show() 

Now, when you run this code, you'll see a plot with a sine wave and a slider below it. Adjusting the slider will change the frequency of the sine wave in real-time. This is a simple example, and you can extend this approach to control more complex visualizations using sliders and other widgets.


More Tags

openpyxl chromium messaging e-commerce allure mailkit primeng-turbotable readonly-attribute neodynamic sympy

More Programming Guides

Other Guides

More Programming Examples