Open In App

Python – Scroll through Plots

Last Updated : 09 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, we can plot graphs using many libraries and functions. Here in this article, our main focus is to add sliders to our plots. But before moving towards the slider, it is necessary to know how to plot a basic plot in Python using matplotlib.pyplot. 

Scrolling through Plots Syntax

The basic syntax of a matplotlib.widget.Slider() is

Syntax: matplotlib.widgets.Slider(axis, label, val_min, val_max, valinit=0.5, valfmt=None, closed_min=True, closed_max=True, slider_min=None, slider_max=None, dragging=True, val_step=None, orientation=’horizontal’,  **kwargs)

What is Scrolling through Plots in Python?

Scroll-through plots are the plots that update themselves as we change the scale of the plot using a slider. A slider can be added to a plot using matplotlib and plotly library. In this tutorial, we will learn about generating sliders using matplotlib.pyplot library. Scroll-through plots may not seem useful or necessary for every case but are surely a beneficial feature. There are cases where the data is huge and cannot fit into a dynamic plot and even if it fits there will be a collision between the points in the plot. Hence, using a slider will reduce collisions between the points and make it look presentable and clean. Also, it will be easy to study.

Slider() Function: Slider() function is a function that is present in matplotlib.widgets and helps the programmer add a slider into the plots.

Python Scrolling through Plots Examples

There are various examples of adding a scroll bar in the matplotlib graph in tkinter Here we are explaining some generally used examples of adding a scroll bar in the matplotlib graph in tkinter those are following.

  • Scroll through Sliders
  • Scroll through Multiple Sliders
  • Scroll through Buttons

Add Scroll bar in Matplotlib Graph in tkinter Using Scroll through Sliders

In this example code utilizes Matplotlib to create a simple plot with a slider. It imports necessary libraries, sets up the plot and axis using subplots, and adjusts the layout. The plot is based on dummy data, and a slider is added with a specified color. The slider’s position is controlled, updating the plot accordingly through the `update` function, which adjusts the x-axis range based on the slider’s value. The final plot is displayed with the slider allowing interactive control over the visible data range.

Python3




# Import libraries using import keyword
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
 
# Setting Plot and Axis variables as subplots()
# function returns tuple(fig, ax)
Plot, Axis = plt.subplots()
 
# Adjust the bottom size according to the
# requirement of the user
plt.subplots_adjust(bottom=0.25)
 
# Set the x and y axis to some dummy data
t = np.arange(0.0, 100.0, 0.1)
s = np.sin(2*np.pi*t)
 
# plot the x and y using plot function
l = plt.plot(t, s)
 
# Choose the Slider color
slider_color = 'White'
 
# Set the axis and slider position in the plot
axis_position = plt.axes([0.2, 0.1, 0.65, 0.03],
                         facecolor = slider_color)
slider_position = Slider(axis_position,
                         'Pos', 0.1, 90.0)
 
# update() function to change the graph when the
# slider is in use
def update(val):
    pos = slider_position.val
    Axis.axis([pos, pos+10, -1, 1])
    Plot.canvas.draw_idle()
 
# update function called using on_changed() function
slider_position.on_changed(update)
 
# Display the plot
plt.show()


Output: 

scroll through plot matplotlib

Add Scroll bar in Matplotlib Graph in tkinter Using Scroll through Multiple Sliders

In this example code creates an interactive plot using Matplotlib with two sliders to control frequency and amplitude of a sine wave. It imports necessary libraries, sets up the plot and sliders, and initializes the plot with dummy data. The sliders are positioned to adjust frequency and amplitude dynamically, and their values are updated using the `update` function. The resulting plot visualizes a sine wave whose frequency and amplitude can be interactively modified through the sliders.

Python3




# Importing Libraries using import function
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
 
# Setting Plot and Axis variables as subplots()
# function returns tuple(fig, ax)
fig, ax = plt.subplots()
 
# Adjust the bottom size according to the
# requirement of the user
plt.subplots_adjust(bottom = 0.25)
 
# Set the x and y axis to some dummy data
t = np.arange(0.0, 1.0, 0.001)
# Initial values of amplitude and frequency
# are denoted by a0 and f0
a0 = 6
f0 = 3
s = a0*np.sin(2*np.pi*f0*t)
 
# plot the x and y using plot function
Plot, = plt.plot(t, s, lw = 3, color = 'green')
plt.axis([0, 1, -10, 10])
 
# Choose the Slider color
axcolor = "White"
 
# Set the frequency and amplitude axis
frequency_axis = plt.axes([0.25, 0.1, 0.65, 0.03],
                          facecolor = axcolor)
amplitude_axis = plt.axes([0.25, 0.15, 0.65, 0.03],
                          facecolor = axcolor)
 
# Set the slider for frequency and amplitude
frequency_slider = Slider(frequency_axis, 'Freq',
                          0.1, 30.0, valinit = f0)
amplitude_slider = Slider(amplitude_axis, 'Amp',
                          0.1, 10.0, valinit = a0)
 
# update() function to change the graph when the
# slider is in use
def update(val):
    amp = amplitude_slider.val
    freq = frequency_slider.val
    Plot.set_ydata(amp*np.sin(2*np.pi*freq*t))
     
# update function called using on_changed() function
# for both frequency and amplitude
frequency_slider.on_changed(update)
amplitude_slider.on_changed(update)
 
# Display the plot
plt.show()


Output: 

scroll thourgh plots

Scroll backwards and forwards through Matplotlib plots

In this example the code creates a Matplotlib plot of a sine wave with an initial display range of 60 data points starting from index 0. It defines a function update_plot to shift the displayed portion of the data either forward or backward by a specified step. Two buttons, “Next” and “Previous,” are added to the plot using matplotlib.widgets.Button. Clicking these buttons triggers the update_plot function, allowing the user to scroll through the data in both directions. The plot dynamically adjusts to ensure the new display range stays within the data bounds

Python3




import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
 
# Generate some example data
x = np.linspace(0, 10, 100)
y = np.sin(x)
 
# Initial display range
display_range = 60
current_index = 0
 
# Create the initial plot
fig, ax = plt.subplots()
line, = ax.plot(x[current_index:current_index + display_range], y[current_index:current_index + display_range], label='sin(x)')
 
# Function to update the plot with the next portion of data
def update_plot(forward=True):
    global current_index
    step = display_range if forward else -display_range
    current_index += step
 
    if current_index < 0:
        current_index = 0
    elif current_index + display_range > len(x):
        current_index = len(x) - display_range
 
    line.set_xdata(x[current_index:current_index + display_range])
    line.set_ydata(y[current_index:current_index + display_range])
    plt.draw()
 
# Create buttons
ax_next_button = plt.axes([0.81, 0.01, 0.1, 0.05])
ax_prev_button = plt.axes([0.7, 0.01, 0.1, 0.05])
 
next_button = Button(ax_next_button, 'Next')
prev_button = Button(ax_prev_button, 'Previous')
 
# Connect buttons to update functions
next_button.on_clicked(lambda event: update_plot(forward=True))
prev_button.on_clicked(lambda event: update_plot(forward=False))
 
# Show the plot
plt.show()


Output :

ezgifcom-video-to-gif-converter-(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads