python matlibplot绘制矩阵_python matplotlib绘制稀疏矩阵模式

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;

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.

Thanks

解决方案

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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值