Search code examples
pythoncolorsmatplotlibsparse-matrix

How to draw a matrix sparsity pattern with color code in python?


I am using spy from matplotlib.pyplot to draw the sparsity pattern of a csc_matrix from scipy.sparse like this

>>> import scipy.sparse as sprs
>>> import matplotlib.pyplot as plt
>>> Matrix=sprs.rand(10,10, density=0.1, format='csc')
>>> plt.spy(Matrix)
>>> plt.show()

I want to do the same but give colors to the matrix elements according to their magnitude. Is there a simple way to make spy do this? If not, is there another way to do it?


Solution

  • You could use imshow:

    d=Matrix.todense()
    plt.imshow(d,interpolation='none',cmap='binary')
    plt.colorbar()
    

    Gives:

    enter image description here