How To Visualize Sparse Matrix in Python?

When you work with sparse matrix data structure with SciPy in Python, sometimes you might want to visualize the sparse matrix. A quick visualization can reveal the pattern in the sparse matrix and can tell how “sparse” the matrix is. And it is a great sanity check.

One way to visualize sparse matrix is to use 2d plot. Python’s matplotlib has a special function called Spy for visualizing sparse matrix. Spy is very similar to matplotlib’s imshow, which is great for plotting a matrix or an array as an image. imshow works with dense matrix, while Spy works with sparse matrix.

Let us first load the modules needed to make sparse matrix and visualize it. We will be using sparse module in SciPy to create sparse matrix and matplotlib’s pyplot to visualize

import matplotlib.pylab as plt
import scipy.sparse as sparse

Let us create simple sparse matrix, here a diagonal sparse matrix with ones along the diagonal with sparse.eye function. We can use the spy function with the sparse matrix as an argument.

# create a sparse diagonal matrix with ones on the diagonal
A = sparse.eye(100)
# visualize the sparse matrix with Spy
plt.spy(A)

It will create 2-D image with blue color squares representing non-zero elements and white color for elements zeros. Since our matrix is diagonal matrix, we see a blue line along the diagonal.

Visualizing Sparse Diagonal Matrix
Visualizing Sparse Diagonal Matrix

Let us create sparse matrix with a specific density

# create a sparse matrix with specific density
A = sparse.random(100,100, density=0.01)
# visualize the sparse matrix with Spy
plt.spy(A)

And visualize this 100×100 sparse matrix with the density 1%.

Sparse Matrix with 1% Density

You can see the blue square is kind of big. We can control the size of the blue squares with the argument “markersize” as shown below. This will help us get a real sense of the actual sparsity of sparse matrix.

A = sparse.random(100,100, density=0.01)
plt.spy(A, markersize=4)

Here is image of same sparse matrix, but with smaller markersize. Now we get a smaller blue square representing the non-zero items and a better sense of the sparsity.

Visualizing sparse matrix: Example 3

Let us create a bigger sparse matrix of dimension 10k x 10k with density of 0.00001.

A = sparse.random(10000,10000, density=0.00001)
plt.spy(A, markersize=1)

Now the visualization of the sparse matrix using Spy is much better with a smaller markersize=1.

Visualizing Sparse matrix with Spy: Example 4