python matplotlib图稀疏矩阵模式

Jin*_*ing 7 python numpy matplotlib scipy sparse-matrix

给定一个稀疏的二进制矩阵A(csr,coo,等等)我想制作一个图,这样我可以看到图中的位置(i,j)= white,如果A(i,j)= 1,和(i, j)= A,如果A(i,j)= 0;

对于密集的numpy数组,matshow将完成这项工作.但是,我的稀疏矩阵(例如100000 x 1000000)的维度很大,可以转换为密集阵列.我想知道如何在稀疏矩阵中绘制模式.

谢谢

Sau*_*tro 18

您可以使用得到一个不错的结果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, 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
Run Code Online (Sandbox Code Playgroud)

请注意,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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 谢谢.这真的很有帮助!! 从你的代码中学到很多:) (2认同)