0
0
Matplotlibdata~5 mins

Widget-based interactions (sliders, buttons) in Matplotlib

Choose your learning style9 modes available
Introduction

Widgets like sliders and buttons let you change your charts live. This helps you explore data easily without writing new code each time.

You want to adjust a chart parameter like line thickness or color interactively.
You want to explore how changing a number affects a graph instantly.
You want to create a simple tool for others to play with data visuals.
You want to demonstrate data changes step-by-step in a presentation.
You want to add interactive controls to a matplotlib plot for better understanding.
Syntax
Matplotlib
from matplotlib.widgets import Slider, Button

# Create slider
slider = Slider(ax_slider, 'Label', valmin, valmax, valinit)

# Create button
button = Button(ax_button, 'Button Label')

Widgets need a special area (axes) on the plot to live in.

You connect widgets to functions that run when you move or click them.

Examples
This creates a slider named 'Value' that goes from 0 to 10 and starts at 5.
Matplotlib
from matplotlib.widgets import Slider

slider = Slider(ax, 'Value', 0, 10, valinit=5)
This creates a button labeled 'Reset' that you can click.
Matplotlib
from matplotlib.widgets import Button

button = Button(ax, 'Reset')
These lines connect the slider and button to functions that run when used.
Matplotlib
slider.on_changed(update_function)
button.on_clicked(reset_function)
Sample Program

This program shows a sine wave. You can change its frequency with the slider. Pressing the reset button returns the frequency to 1.

Matplotlib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button

# Create data
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x)

# Create plot
fig, ax = plt.subplots()
line, = ax.plot(x, y, lw=2)
ax.set_title('Sine Wave with Adjustable Frequency')

# Adjust plot to make room for widgets
plt.subplots_adjust(left=0.1, bottom=0.3)

# Slider axis
axfreq = plt.axes([0.1, 0.15, 0.8, 0.05])
slider = Slider(axfreq, 'Freq', 0.1, 5.0, valinit=1)

# Button axis
axbutton = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(axbutton, 'Reset')

# Update function for slider
 def update(val):
     freq = slider.val
     line.set_ydata(np.sin(freq * x))
     fig.canvas.draw_idle()

slider.on_changed(update)

# Reset function for button
 def reset(event):
     slider.reset()

button.on_clicked(reset)

plt.show()
OutputSuccess
Important Notes

Widgets only work in interactive environments like Jupyter notebooks or Python scripts run locally.

Make sure to leave space on the plot for widgets using plt.subplots_adjust.

Use fig.canvas.draw_idle() to update the plot smoothly after widget changes.

Summary

Widgets let you change plot details live without rewriting code.

Sliders adjust values continuously; buttons trigger actions on click.

Connect widgets to functions to update your plot interactively.