python matplotlib绘制稀疏矩阵模式 [英] python matplotlib plot sparse matrix pattern
问题描述
给出一个稀疏的二进制矩阵A(csr,coo等),我想绘制一个图,以便在A(i,j)= 1的情况下可以看到图中的位置(i,j)=白色. (i,j)=黑色,如果A(i,j)= 0;
Given a sparse binary matrix A (csr, coo, whatever) I want to make a plot such that I can see the position (i,j) = white in the figure if A(i,j) = 1, and (i,j) = black if A(i,j) = 0;
对于密集的numpy数组,matshow将完成这项工作.但是,我的稀疏矩阵的维数(例如100000 x 1000000)太大,无法转换为密集数组.我不知道如何在稀疏矩阵中绘制图案.
For a dense numpy array, matshow will do the job. However, the dimension of my sparse matrix (say 100000 x 1000000) is to big to be converted to a dense array. I wonder how could I plot the pattern in my sparse matrix.
谢谢
推荐答案
使用coo_matrix
,plot()
和一些调整,您可以得到不错的结果:
You can get a nice result using a coo_matrix
, plot()
and some adjustments:
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
轴反转以将第一行放在图的顶部.一个例子:
Note that the y
axis is inverted to put the first row at the top of the figure. One example:
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绘制稀疏矩阵模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!