python matplotlib 绘制稀疏矩阵模式

标签 python numpy matplotlib scipy sparse-matrix

给定一个稀疏二进制矩阵 A (csr, coo, whatever) 我想绘制一个图,如果 A(i,j) = 1,我可以看到图中的位置 (i,j) = white,并且(i,j) = 黑色如果 A(i,j) = 0;

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

谢谢

最佳答案

您可以使用 coo_matrixplot() 和一些调整来获得不错的结果:

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()

enter image description here

关于python matplotlib 绘制稀疏矩阵模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22961541/

相关文章:

python - Azure Functions (python) adal 身份验证超时

python - 如何使用 SQLAlchemy 将关系对象数据插入数据库?

python - a 和 b 的任意值使得 (a in b and b in a)==True

python - numpy.transpose 是否在内存中重新排序数据?

python - python中的循环缓冲区比使用双端队列的缓冲区快?

python - 在 matplotlib 图的交互式导航中保留缩放设置

python - 是否可以从模块中删除方法?

python - 使用数组的 Numpy 索引

python-3.x - Plot_confusioin_matrix 图不显示整数值,而是显示一些指数值

python - 没有 fillcolor 无法在 python 中绘制椭圆