Interactive Plots in Matplotlib
Adding interactivity to plots can make your visualizations more engaging and informative. Matplotlib offers several tools, such as widgets and event handling, to create interactive plots.
Using Matplotlib Widgets
Widgets in Matplotlib allow users to interact with plots by adding sliders, buttons, and checkboxes.
Example 1: Slider to Adjust a Plot
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider
# Data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create figure and plot
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
line, = ax.plot(x, y, label='Sine Wave')
ax.set_title("Interactive Sine Wave")
ax.legend()
# Add a slider
ax_slider = plt.axes([0.2, 0.1, 0.65, 0.03])
slider = Slider(ax_slider, 'Frequency', 0.1, 2.0, valinit=1.0)
# Update function
def update(val):
freq = slider.val
line.set_ydata(np.sin(freq * x))
fig.canvas.draw_idle()
slider.on_changed(update)
plt.show()
Adding Buttons for Actions
Buttons can trigger specific actions, such as resetting a plot or changing its properties.
Example 2: Reset Button
from matplotlib.widgets import Button
# Data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create figure and plot
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
line, = ax.plot(x, y, label='Sine Wave')
ax.set_title("Interactive Sine Wave with Reset")
ax.legend()
# Add a button
ax_button = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(ax_button, 'Reset')
# Reset function
def reset(event):
line.set_ydata(np.sin(x))
slider.reset()
fig.canvas.draw_idle()
button.on_clicked(reset)
plt.show()
Checkboxes for Display Options
Checkboxes allow users to toggle the visibility of different elements in a plot.
Example 3: Toggle Plot Visibility
from matplotlib.widgets import CheckButtons
# Data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Create figure and plot
fig, ax = plt.subplots()
line1, = ax.plot(x, y1, label='Sine Wave')
line2, = ax.plot(x, y2, label='Cosine Wave', linestyle='--')
ax.legend()
# Add checkboxes
ax_check = plt.axes([0.8, 0.4, 0.15, 0.15])
check = CheckButtons(ax_check, ['Sine', 'Cosine'], [True, True])
# Toggle visibility function
def toggle(label):
if label == 'Sine':
line1.set_visible(not line1.get_visible())
elif label == 'Cosine':
line2.set_visible(not line2.get_visible())
fig.canvas.draw_idle()
check.on_clicked(toggle)
plt.show()
Event Handling in Matplotlib
Matplotlib provides event handling to capture user interactions like mouse clicks and key presses.
Example 4: Capture Mouse Clicks
# Data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create figure and plot
fig, ax = plt.subplots()
line, = ax.plot(x, y, label='Sine Wave')
ax.set_title("Click to Annotate")
# Event handling function
def on_click(event):
if event.inaxes == ax:
ax.annotate(f"({event.xdata:.2f}, {event.ydata:.2f})",
(event.xdata, event.ydata),
textcoords="offset points",
xytext=(10, 10),
arrowprops=dict(arrowstyle='->', color='red'))
fig.canvas.draw()
fig.canvas.mpl_connect('button_press_event', on_click)
plt.show()
Practical Applications
Example 5: Interactive Data Visualization
Use sliders and buttons to adjust data range and refresh plots dynamically.
Example 6: Real-Time Plot Updates
Implement event handlers to dynamically update plots based on user input or external events.
Try It Yourself
Problem 1: Interactive Scatter Plot
Create an interactive scatter plot where users can change the size of the points using a slider.
Show Code
# Data
x = np.random.rand(50)
y = np.random.rand(50)
sizes = np.full(50, 100)
# Create figure and scatter plot
fig, ax = plt.subplots()
scatter = ax.scatter(x, y, s=sizes, alpha=0.5)
# Add slider
ax_slider = plt.axes([0.2, 0.02, 0.65, 0.03])
slider = Slider(ax_slider, 'Size', 10, 300, valinit=100)
# Update function
def update(val):
scatter.set_sizes(np.full(50, slider.val))
fig.canvas.draw_idle()
slider.on_changed(update)
plt.show()
Problem 2: Interactive Line Plot with Reset
Create an interactive line plot where users can adjust the frequency and reset it to default values.
Show Code
# Data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create figure and plot
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
line, = ax.plot(x, y, label='Sine Wave')
ax.set_title("Interactive Line Plot with Reset")
ax.legend()
# Add slider
ax_slider = plt.axes([0.2, 0.1, 0.65, 0.03])
slider = Slider(ax_slider, 'Frequency', 0.1, 2.0, valinit=1.0)
# Add button
ax_button = plt.axes([0.8, 0.02, 0.1, 0.04])
button = Button(ax_button, 'Reset')
# Update function
def update(val):
freq = slider.val
line.set_ydata(np.sin(freq * x))
fig.canvas.draw_idle()
slider.on_changed(update)
# Reset function
def reset(event):
slider.reset()
line.set_ydata(np.sin(x))
fig.canvas.draw_idle()
button.on_clicked(reset)
plt.show()
Interactive plots enhance user engagement and allow for dynamic data exploration. Experiment with different widgets and event handlers to create powerful visualizations!