The Wayback Machine - https://web.archive.org/web/20240823220354/https://www.geeksforgeeks.org/matplotlib-plot-zooming-with-scroll-wheel/
Open In App

Matplotlib – Plot zooming with scroll wheel

Last Updated : 02 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Matplotlib is a Python library for data visualization and plotting, and MPL Interactions is a Python library for providing useful methods for interacting with Matplotlib plots. In this article, we will use MPL Interactions and the Matplotlib library to plot a graph that can be zoomed in with the mouse wheel. If Matplotlib and MPL Interactions are not installed on your system, please install them before plotting the graphs.

Required Packages

In the command prompt or terminal install the Matplotlib and MPL Interactions library using the following command:

pip install matplotlib
pip install mpl-interactions

Approaches

Below are approaches that we followed to Plot a graph with the ability to zoom with the scroll wheel.

  • Importing necessary library.
  • Create the dataset or you can load your own dataset for plotting the graph.
  • Enable scroll to zoom with the help of MPL Interactions library functions like off and zoom_factory.
  • Enable scrolling and panning with the help of the MPL Interactions library function like a panhandler.

Plot a Graph that can be Zoomed in with the Scroll Wheel

Importing necessary library. Create the dataset or you can load your own dataset for plotting the graph. Enable scroll to zoom with the help of MPL Interactions library functions like off and zoom_factory. Enable scrolling and panning with the help of the MPL Interactions library function like a panhandler.

Python3




# Importing required library
from mpl_interactions import ioff, panhandler, zoom_factory
import matplotlib.pyplot as plt
%matplotlib widget
 
# creating the dataset
data = {'Operating System': 10, 'Data Structure': 7,
        'Machine Learning': 14, 'Deep Learning': 12}
courses = list(data.keys())
values = list(data.values())
# Enable scroll to zoom with the help of MPL
# Interactions library function like ioff and zoom_factory.
with plt.ioff():
    figure, axis = plt.subplots()
# creating the bar plot
plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")
plt.bar(courses, values, color='green', width=0.4)
disconnect_zoom = zoom_factory(axis)
# Enable scrolling and panning with the help of MPL
# Interactions library function like panhandler.
pan_handler = panhandler(figure)
display(figure.canvas)


Output:

Plot zooming with scroll wheel

 

Enable Zoomed-in with the Scroll Wheel using ScrollZoom 

Importing necessary library. Create the dataset or you can load your own dataset for plotting the graph. Plotting Graph for Created Dataset or Loaded Dataset Enable zoomed-in with the scroll wheel by setup the config={‘scrollZoom’: True} in the figure configuration.

Python3




# Importing library
import plotly.express as px
import pandas as pd
# initialise data of lists.
data = {'Subject': ["Data Analysis", "Data Science",
                    "Machine Learning", "Data Structure",
                    "Web Design", "Android Development"],
        'Total Student': [5, 10, 15, 20, 25, 30],
        'Male Student': [3, 4, 7, 10, 5, 17],
        'Female Student': [2, 6, 8, 10, 20, 13]}
 
# Create DataFrame
df = pd.DataFrame(data)
 
# Plotting Bar Plot for created Dataset With
# Enabled Scroll Zoom
plot = px.bar(df, x="Subject", y="Total Student",
              title="Plot With Enabled Scroll Zoom",
              color="Subject")
 
# Showing Scatter Plot with Scroll Zoom.
plot.show(config={'scrollZoom': True})


Output:

Plot zooming with scroll wheel

 



Similar Reads

Wheel Graph using Networkx Python
A wheel graph is a type of graph in which if we connect each node in an n-1 node cycle graph to nth node kept at the centre we get a wheel graph. The definition would be more clear after seeing the example below. Wheel Graph with n nodes is represented by Wn . Example: W5: W6: Properties of Wheel Graph: Total number of edges are 2(N-1)It is a plana
2 min read
What is a Python wheel?
Python wheels are a pre-built binary package format for Python modules and libraries. They are designed to make it easier to install and manage Python packages, by providing a convenient, single-file format that can be downloaded and installed without the need to compile the package from source code. They are designed to replace the older egg forma
6 min read
PyQtGraph - Getting Plot Item from Plot Window
In this article we will see how we can get the plot item of plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and s
2 min read
Time Series Plot or Line plot with Pandas
Prerequisite: Create a Pandas DataFrame from Lists Pandas is an open-source library used for data manipulation and analysis in Python. It is a fast and powerful tool that offers data structures and operations to manipulate numerical tables and time series. Examples of these data manipulation operations include merging, reshaping, selecting, data cl
6 min read
Pandas Scatter Plot – DataFrame.plot.scatter()
A Scatter plot is a type of data visualization technique that shows the relationship between two numerical variables. For plotting to scatter plot using pandas there is DataFrame class and this class has a member called plot. Calling the scatter() method on the plot member draws a plot between two variables or two columns of pandas DataFrame. Synta
2 min read
Plot 2D data on 3D plot in Python
In this article, we will be learning about how to plot 2D data on 3D plot in Python. We will be demonstrating two methods in order to learn the concept. The first method will be using Matplotlib.pyplot.gca() function which is a pyplot module of the matplotlib library. But before that, we need to configure where are we going to create our project an
4 min read
Pandas - Plot multiple time series DataFrame into a single plot
In this article, we are going to see how to plot multiple time series Dataframe into single plot. If there are multiple time series in a single DataFrame, you can still use the plot() method to plot a line chart of all the time series. To Plot multiple time series into a single plot first of all we have to ensure that indexes of all the DataFrames
4 min read
How to add a legend to a scatter plot in Matplotlib ?
In this article, we are going to add a legend to the depicted images using matplotlib module. We will use the matplotlib.pyplot.legend() method to describe and label the elements of the graph and distinguishing different plots from the same graph. Syntax: matplotlib.pyplot.legend( ["title_1", "Title_2"], ncol = 1 , loc = "upper left" ,bbox_to_ancho
2 min read
How to Place Legend Outside of the Plot in Matplotlib?
In this article, we will see how to put the legend outside the plot. Let's discuss some concepts : Matplotlib: Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John H
3 min read
Matplotlib.axes.Axes.plot() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. Example: import datetime import matplotlib.pyplot
2 min read
Make a violin plot in Python using Matplotlib
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc. Note: For more information, refer to Python Matplotlib – An Overview Wh
3 min read
Plot the magnitude spectrum in Python using Matplotlib
A Signal is an electromagnetic field or an electric current to transmit data. There are various components of a signal such as frequency, amplitude, wavelength, phase, angular frequency and period from which it is described. A periodic signal can be represented using the below sine function: y = A sin(w*t + Q) In which A represents the amplitude(in
3 min read
Plot the phase spectrum in Python using Matplotlib
A Signal is an electromagnetic field or an electric current to transmit data. There are various components of a signal such as frequency, amplitude, wavelength, phase, angular frequency and period from which it is described. A periodic signal can be represented using the below sine function: y = A sin(w*t + Q) In which A represents the amplitude(in
3 min read
Plot Mathematical Expressions in Python using Matplotlib
For plotting equations we will use two modules Matplotlib.pyplot and Numpy. This module helps you to organize your Python code logically. Numpy Numpy is a core library used in Python for scientific computing. This Python library supports you for a large, multidimensional array object, various derived objects like matrices and masked arrays, and ass
5 min read
Plot the power spectral density using Matplotlib - Python
matplotlib.pyplot.psd() function is used to plot power spectral density. In the Welch's average periodogram method for evaluating power spectral density (say, Pxx), the vector 'x' is divided equally into NFFT segments. Every segment is windowed by the function window and detrended by the function detrend. The overlap between segments is given by 'n
6 min read
Contour Plot using Matplotlib - Python
Contour plots also called level plots are a tool for doing multivariate analysis and visualizing 3-D plots in 2-D space. If we consider X and Y as our variables we want to plot then the response Z will be plotted as slices on the X-Y plane due to which contours are sometimes referred as Z-slices or iso-response. Contour plots are widely used to vis
2 min read
Quiver Plot in Matplotlib
Quiver plot is basically a type of 2D plot which shows vector lines as arrows. This type of plots are useful in Electrical engineers to visualize electrical potential and show stress gradients in Mechanical engineering. Creating a Quiver Plot Let's start creating a simple quiver plot containing one arrow which will explain how Matplotlib's ax.quive
5 min read
Tri-Surface Plot in Python using Matplotlib
A Tri-Surface Plot is a type of surface plot, created by triangulation of compact surfaces of finite number of triangles which cover the whole surface in a manner that each and every point on the surface is in triangle. The intersection of any two triangles results in void or a common edge or vertex. This type of plot is created where the evenly sa
2 min read
Plot a quadrilateral mesh in Python using Matplotlib
Matplotlib a multiplatform data visualization library built on NumPy arrays, and designed to work with the broader SciPy stack. Matplotlib has the ability to play well with many operating systems and graphics backends as well. matplotlib.pyplot can also be used for MATLAB-like plotting framework. Plotting a quadrilateral mesh pcolormesh() function
3 min read
Create a pseudocolor plot of an unstructured triangular grid in Python using Matplotlib
Matplotlib is a Python module which can be used for data visualization; and analyse the data graphically in the form of pie-chart, histogram, bar graph and many more. It also has an ability to generate MATLAB-like frameworks. Unstructured triangular grid An unstructured triangular grid contains n_points points and n_tri triangles which can either b
5 min read
Autocorrelation plot using Matplotlib
Autocorrelation plots are a commonly used tool for checking randomness in a data set. This randomness is ascertained by computing autocorrelations for data values at varying time lags. Characteristics Of Autocorrelation Plot : It measures a set of current values against a set of past values and finds whether they correlate.It is the correlation of
3 min read
Plot a Vertical line in Matplotlib
Matplotlib is a popular python library used for plotting, It provides an object-oriented API to render GUI plots. Plotting a horizontal line is fairly simple, The following code shows how it can be done. Making a single vertical line Method #1: Using axvline() This function adds the vertical lines across the axes of the plot Syntax: matplotlib.pypl
4 min read
Plot a Horizontal line in Matplotlib
Matplotlib is a popular python library used for plotting, It provides an object-oriented API to render GUI plots Plotting a horizontal line is fairly simple, Using axhline() The axhline() function in pyplot module of matplotlib library is used to add a horizontal line across the axis. Syntax: matplotlib.pyplot.axhline(y, color, xmin, xmax, linestyl
2 min read
How to Add Markers to a Graph Plot in Matplotlib with Python?
In this article, we will learn how to add markers to a Graph Plot in Matplotlib with Python. For that just see some concepts that we will use in our work. Graph Plot: A plot is a graphical technique for representing a data set, usually as a graph showing the relationship between two or more variables.Markers: The markers are shown in graphs with di
2 min read
How to Change the Line Width of a Graph Plot in Matplotlib with Python?
Prerequisite : Matplotlib In this article we will learn how to Change the Line Width of a Graph Plot in Matplotlib with Python. For that one must be familiar with the given concepts: Matplotlib : Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on
2 min read
How to Change the Transparency of a Graph Plot in Matplotlib with Python?
Matplotlib is a library in Python and it is numerical — mathematical extension for NumPy library. Pyplot is a state-based interface to a matplotlib module which provides a MATLAB-like interface. There are various plots that can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. In order to change the transparency of a graph
3 min read
How To Highlight a Time Range in Time Series Plot in Python with Matplotlib?
A time series plot is a plot which contains data which is being measured over a period of time, for example, a gross domestic product of a country, the population of the world and many other data. Sometimes we want to highlight a specific period of the timeline so that it is easier for the observer to read specific data. We can highlight a time ran
4 min read
How to generate a random color for a Matplotlib plot in Python?
Handling huge dataset requires libraries and methods that can be used to store, analyze and manipulate the datasets. Python is a popular choice when it comes to data science and analytics. Data scientists prefer Python due to its wide library support that contains functions which can be used to work with datasets to create graphs and charts. Matplo
3 min read
How to Set Plot Background Color in Matplotlib?
Prerequisites: MatplotlibNumpy From the below figure one can infer that a plot consists of X-axis, Y-axis, plot title and the axes. By default, the color of the plot is white. If we have to set the background color of the plot so that our plot looks beautiful, we have to make the axes object, by using axes() attribute after plotting the graph. Appr
4 min read
How to plot two histograms together in Matplotlib?
Creating the histogram provides the visual representation of data distribution. By using a histogram we can represent a large amount of data and its frequency as one continuous plot. How to plot a histogram using Matplotlib For creating the Histogram in Matplotlib we use hist() function which belongs to pyplot module. For plotting two histograms to
3 min read
Practice Tags :
three90RightbarBannerImg