Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How To Visualize Sparse Matrix in Python using Matplotlib?

  • Difficulty Level : Hard
  • Last Updated : 27 Apr, 2020

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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.


Zarray-like (M, N)The array to be plotted
Precisionfloat or ‘present’, optional
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
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
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.

    agg_filtera filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
    alphafloat or None
    clip_pathPatch or (Path, Transform) or None
    dash_capstyle{‘butt’, ’round’, ‘projecting’}
    dash_joinstyle{‘miter’, ’round’, ‘bevel’}
    dashessequence 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’}
    fillstyle{‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’}
    linestyle{‘-‘, ‘–‘, ‘-.’, ‘:’, ”, (offset, on-off-seq), …}
    markermarker style
    markeveryNone or int or (int, int) or slice or List[int] or float or (float, float)
    path_effectsAbstract path effects
    pickerfloat or callable[[Artist, Event], Tuple[bool, dict]]
    rasterizedbool or None
    sketch_params(scale: float, length: float, randomness: float)
    snapbool or None
    solid_capstyle{‘butt’, ’round’, ‘projecting’}
    solid_joinstyle{‘miter’, ’round’, ‘bevel’}
    xdata1D array
    ydata1D array

    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.

    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)

    Visualize sparse matrix python

    My Personal Notes arrow_drop_up
    Recommended Articles
    Page :

    Start Your Coding Journey Now!