Skip to content

Instantly share code, notes, and snippets.

@isayev
Created April 28, 2014 04:40
Show Gist options
  • Select an option

  • Save isayev/11361949 to your computer and use it in GitHub Desktop.

Select an option

Save isayev/11361949 to your computer and use it in GitHub Desktop.
plot sparse matrix pattern
import matplotlib.pyplot as plt
from scipy.sparse import coo_matrix
def plot_coo_matrix(m):
if not isinstance(m, coo_matrix):
m = coo_matrix(m)
fig = plt.figure()
ax = fig.add_subplot(111, axisbg='black')
ax.plot(m.col, m.row, 's', color='white', ms=1)
ax.set_xlim(0, m.shape[1])
ax.set_ylim(0, m.shape[0])
ax.set_aspect('equal')
for spine in ax.spines.values():
spine.set_visible(False)
ax.invert_yaxis()
ax.set_aspect('equal')
ax.set_xticks([])
ax.set_yticks([])
return ax
shape = (100000, 100000)
rows = np.int_(np.round_(shape[0]*np.random.random(1000)))
cols = np.int_(np.round_(shape[1]*np.random.random(1000)))
vals = np.ones_like(rows)
m = coo_matrix((vals, (rows, cols)), shape=shape)
ax = plot_coo_matrix(m)
ax.figure.show()
@qingfengxia
Copy link

add "import numpy as np" at the beginning

replace the last with this to plot without error, still a warning for matplotlib 2
#ax.figure.show()
plt.show()

@falcorocks
Copy link

@qingfengxia thanks dude, fixed it for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment