给定一个稀疏二进制矩阵 A (csr, coo, whatever) 我想绘制一个图,如果 A(i,j) = 1,我可以看到图中的位置 (i,j) = white,并且(i,j) = 黑色如果 A(i,j) = 0;
对于密集的 numpy 数组,matshow 将完成这项工作。但是,我的稀疏矩阵(比如 100000 x 1000000)的维度太大,无法转换为密集数组。我想知道如何在我的稀疏矩阵中绘制模式。
谢谢
最佳答案
您可以使用 coo_matrix
、plot()
和一些调整来获得不错的结果:
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, facecolor='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
请注意,y
轴是倒转的,以便将第一行放在图的顶部。一个例子:
import numpy as np
from scipy.sparse import coo_matrix
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()
关于python matplotlib 绘制稀疏矩阵模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22961541/