The Wayback Machine - https://web.archive.org/web/20241117162640/https://www.geeksforgeeks.org/how-to-visualize-sparse-matrix-in-python-using-matplotlib/
Open In App

How To Visualize Sparse Matrix in Python using Matplotlib?

Last Updated : 27 Apr, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Visualize Sparse Matrix using Matplotlib

Spy is a function used to visualize the array as an image similar to matplotlib imshow function, but it is used in case of sparse matrix instead of dense matrix. A sparse matrix is a matrix where most of the elements are zero.

Sparse matrix and its representation

Spy function uses two plotting styles to visualize the array, these are:

  • Image style
  • Marker style

Both the styles can be used for full arrays but in case of spmatrix instances only the marker style works. If marker or markersize is None then imshow function is used, and all the remaining keyword arguments are passed to this function; else, a Line2D object will be returned with the value of marker determining the marker type, and any remaining keyword arguments passed to plot function.

Syntax: matplotlib.pyplot.spy(Z, precision=0, marker=None, markersize=None, aspect=’equal’, origin=’upper’, \*\*kwargs)

Return value:

The return type depends on the plotting style, i.e. AxesImage or Line2D.

Parameters:

Parameter Value Use
Z array-like (M, N) The array to be plotted
Precision float or ‘present’, optional
default:zero
If precision is 0, any non-zero value will be plotted; else, values of |Z| > precision will be plotted.
For spmatrix instances, there is a special case: if precision is ‘present’, any value present in the array will be plotted, even if it is identically zero.
Origin {‘upper’, ‘lower’}, optional
default:’upper’
Place the [0, 0] index of the array in the upper left or lower left corner of the axes.
Aspect {‘equal’, ‘auto’, None} or float, optional
default:’equal’
It controls the aspect ratio of the axes. The aspect is of particular relevance for images since it may distort the image, i.e. pixel will not be square.

  • ‘equal’: Ensures an aspect ratio of 1. Pixels will be square.
  • ‘auto’: The axes is kept fixed and the aspect is adjusted so that the data fit in the axes. In general, this will result in non-square pixels.
  • None: Use rcParams[“image.aspect”]
  • Other parameters: **kwargs

    These are the additional parameters that helps to get different plotting styles.

    Property Description
    agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
    alpha float or None
    animated bool
    antialiased bool
    clip_box Bbox
    clip_on bool
    clip_path Patch or (Path, Transform) or None
    color color
    contains callable
    dash_capstyle {‘butt’, ’round’, ‘projecting’}
    dash_joinstyle {‘miter’, ’round’, ‘bevel’}
    dashes sequence of floats (on/off ink in points) or (None, None)
    data (2, N) array or two 1D arrays
    drawstyle {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}
    figure figure
    fillstyle {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’}
    grid str
    in_layout bool
    label object
    linestyle {‘-‘, ‘–‘, ‘-.’, ‘:’, ”, (offset, on-off-seq), …}
    linewidth float
    marker marker style
    markeredgecolor color
    markeredgewidth float
    markerfacecolor color
    markerfacecoloralt color
    markersize float
    markevery None or int or (int, int) or slice or List[int] or float or (float, float)
    path_effects Abstract path effects
    picker float or callable[[Artist, Event], Tuple[bool, dict]]
    pickradius float
    rasterized bool or None
    sketch_params (scale: float, length: float, randomness: float)
    snap bool or None
    solid_capstyle {‘butt’, ’round’, ‘projecting’}
    solid_joinstyle {‘miter’, ’round’, ‘bevel’}
    transform matplotlib.transforms.Transform
    url str
    visible bool
    xdata 1D array
    ydata 1D array
    zorder float

    Example 1:




    # Implementation of matplotlib spy function
    import matplotlib.pyplot as plt
    import numpy as np
      
      
    x = np.random.randn(50, 50)
      
    x[15, :] = 0.
    x[:, 40] = 0.
      
    plt.spy(x)

    
    

    Output:
    Visualize sparse matrix python

    Example 2:




    # Implementation of matplotlib spy function
    import matplotlib.pyplot as plt
    import numpy as np
      
    x = np.random.randn(50, 50)
    x[15, :] = 0.
    x[:, 40] = 0.
      
    plt.spy(x, precision = 0.1, markersize = 5)

    
    

    Output:
    Visualize sparse matrix python



    Similar Reads

    Python | Visualize graphs generated in NetworkX using Matplotlib
    Prerequisites: Generating Graph using Network X, Matplotlib IntroIn this article, we will be discussing how to plot a graph generated by NetworkX in Python using Matplotlib. NetworkX is not a graph visualizing package but basic drawing with Matplotlib is included in the software package. Step 1 : Import networkx and matplotlib.pyplot in the project
    3 min read
    How to visualize data from MySQL database by using Matplotlib in Python ?
    Prerequisites: Matplotlib in Python, MySQL While working with Python we need to work with databases, they may be of different types like MySQL, SQLite, NoSQL, etc. In this article, we will be looking forward to how to connect MySQL databases using MySQL Connector/Python. MySQL Connector module of Python is used to connect MySQL databases with the P
    5 min read
    Analyze and Visualize Earthquake Data in Python with Matplotlib
    Earthquake is a natural phenomenon whose occurrence predictability is still a hot topic in academia. This is because of the destructive power it holds. In this article, we'll learn how to analyze and visualize earthquake data with Python and Matplotlib. Importing Libraries and Dataset Python libraries make it very easy for us to handle the data and
    3 min read
    How to visualize selection and insertion sort using Tkinter in Python?
    In this article, we are going to create a GUI application that will make us visualize and understand two of the most popular sorting algorithms better, using Tkinter module. Those two sorting algorithms are selection sort and insertion sort. Selection sort and Insertion sort are the two most popular algorithms. Selection sort is a comparison-based
    6 min read
    Visualize sinusoidal waves using Python
    Sinusoidal waves are the most basic trigonometric periodic curves, which is also known as the sine curve. Here we will see how sine function is related to a circle. Even though the sine function is a trigonometric function, it has more to do with a circle rather than a triangle. Consider a simple equation of a circle: [Tex]x^2 + y^2 = r^2 [/Tex] wh
    5 min read
    Visualize Merge sort Using Tkinter in Python
    Prerequisites: Python GUI – tkinter In this article, we will create a GUI application that will help us to visualize the algorithm of merge sort using Tkinter in Python. Merge Sort is a popular sorting algorithm. It has a time complexity of N(logN) which is faster than other sorting algorithms like a bubble or selection sort. By creating this appli
    5 min read
    Sparse Matrix in Python using Dictionary
    A sparse matrix is a matrix in which most of the elements have zero value and thus efficient ways of storing such matrices are required. Sparse matrices are generally utilized in applied machine learning such as in data containing data-encodings that map categories to count and also in entire subfields of machine learning such as natural language p
    2 min read
    Saving a Networkx graph in GEXF format and visualize using Gephi
    Prerequisites: Networkx NetworkX is a Python language software package for the creation, manipulation, and study of the structure, dynamics, and function of complex networks. It is used to study large complex networks represented in form of graphs with nodes and edges. Using networkx we can load and store complex networks. We can generate many type
    2 min read
    Visualize Graphs in Python
    Prerequisites: Graph Data Structure And Algorithms A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. In this tutorial we are going to visualize undirected Graphs in Python with the help of networkx librar
    2 min read
    Visualize data from CSV file in Python
    CSV stands for 'Comma-Separated Values'. It means the data(values) in a CSV file are separated by a delimiter i.e., comma. Data in a CSV file is stored in tabular format with an extension of .csv. Generally, CSV files are used with Google spreadsheets or Microsoft Excel sheets. A CSV file contains a number of records with the data spread across row
    4 min read
    How to reduce dimensionality on Sparse Matrix in Python?
    A matrix usually consists of a combination of zeros and non-zeros. When a matrix is comprised mostly of zeros, then such a matrix is called a sparse matrix. A matrix that consists of maximum non-zero numbers, such a matrix is called a dense matrix. Sparse matrix finds its application in high dimensional Machine learning and deep learning problems.
    3 min read
    SciPy - Sparse Matrix Multiplication
    Sparse matrices are those matrices that have the most of their elements as zeroes. scipy.sparse is SciPy 2-D sparse matrix package for numeric data. It provides us different classes to create sparse matrices. csc_matrix and csr_matrix are the two such classes. csc_matrix() is used to create a compressed sparse column matrix whereas csr_matrix() is
    4 min read
    Compressed Sparse formats CSR and CSC in Python
    In Python, two of the most commonly used sparse matrix formats are Compressed Sparse Row (CSR) and Compressed Sparse Column (CSC). This article will explore the differences between CSR and CSC formats, their use cases, and how to work with them using Python's SciPy library. Difference Between CSR and CSC FormatsCharacteristics CSR Formats CSC Forma
    3 min read
    SciPy CSGraph – Compressed Sparse Graph
    Graphs are powerful mathematical structures used to represent relationships between entities in various fields, including computer science, social networks, transportation systems, and more. Analyzing and computing graphs is a fundamental task in many applications, but it can be challenging, especially when dealing with large graphs with sparse con
    9 min read
    Convert covariance matrix to correlation matrix using Python
    In this article, we will be discussing the relationship between Covariance and Correlation and program our own function for calculating covariance and correlation using python.  Covariance: It tells us how two quantities are related to one another say we want to calculate the covariance between x and y the then the outcome can be one of these. [Tex
    5 min read
    Visualizing Tiff File Using Matplotlib and GDAL using Python
    Tiff file formats are used for storing raster images. A library called GDAL- Geospatial Data Abstraction Library is specially used for the purpose of reading such raster files along with other file formats like vector formats. The gdal module belongs to Open Source Geospatial Foundation To install this module run this command into your terminal. pi
    2 min read
    Violinplot in Python using axes class of Matplotlib
    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. #Sample Code # Implementation of matplotlib functi
    2 min read
    3D Wireframe plotting in Python using Matplotlib
    To create static, animated and interactive visualizations of data, we use the Matplotlib module in Python. The below programs will depict 3D wireframe. visualization of data in Python. In-order to visualize data using 3D wireframe we require some modules from matplotlib, mpl_toolkits and numpy library. Example 1: C/C++ Code # importing modules from
    1 min read
    Multiplots in Python using Matplotlib
    Matplotlib is a Python library that can be used for plotting graphs and figures. Plotting multiplots or multiple plots are often required either for comparing the two curves or show some gradual changes in the multiple plots, and this can be done using Subplots. Subplots are one of the most important and fundamental concepts to be understood while
    3 min read
    Python | Matplotlib Sub plotting using object oriented API
    Plotting using Object Oriented(OO) API in matplotlib is an easy approach to plot graphs and other data visualization methods. The simple syntax to create the class and object for sub-plotting is - class_name, object_name = matplotlib.pyplot.subplots('no_of_rows', 'no_of_columns') Let's take some examples to make it more clear. Example #1: # importi
    2 min read
    Python | Working with PNG Images using 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 Hunter in the year 2002. One of the greatest benefits of visualization is that it allows us visual access to hug
    3 min read
    Python | Matplotlib Graph plotting using object oriented API
    In object-oriented API, first, we create a canvas on which we have to plot the graph and then we plot the graph. Many people prefer object-oriented API because it is easy to use as compared to functional API. Let's try to understand this with some examples. Example #1: # importing matplotlib library import matplotlib.pyplot as plt # x axis values x
    2 min read
    Python | Basic Gantt chart using Matplotlib
    Prerequisites : Matplotlib IntroductionIn this article, we will be discussing how to plot a Gantt Chart in Python using Matplotlib.A Gantt chart is a graphical depiction of a project schedule or task schedule (In OS). It's is a type of bar chart that shows the start and finish dates of several elements of a project that include resources or deadlin
    3 min read
    Save multiple matplotlib figures in single PDF file using Python
    In this article, we will discuss how to save multiple matplotlib figures in a single PDF file using Python. We can use the PdfPages class's savefig() method to save multiple plots in a single pdf. Matplotlib plots can simply be saved as PDF files with the .pdf extension. This saves Matplotlib-generated figures in a single PDF file named Save multip
    3 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
    3D Contour Plotting in Python using Matplotlib
    Matplotlib was introduced keeping in mind, only two-dimensional plotting. But at the time when the release of 1.0 occurred, the 3d utilities were developed upon the 2d and thus, we have 3d implementation of data available today! The 3d plots are enabled by importing the mplot3d toolkit. Let's look at a 3d contour diagram of a 3d cosine function. Th
    2 min read
    Make filled polygons between two curves in Python using 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.To create filled polygons between two curves a PolyCollection filling needs to be created between y1 and y2.Parameters for the above task:
    1 min read
    three90RightbarBannerImg