如何在matplotlib matshow中更改矩阵某些元素的颜色? [英] How to change colour of certain elements of a matrix in matplotlib matshow?

查看:556
本文介绍了如何在matplotlib matshow中更改矩阵某些元素的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二部图(分别为1和0)和两簇(行和列的数组的数组)的邻接矩阵.如何使用matplotlib matshow为邻接矩阵中属于不同簇的元素(仅1个)设置不同的颜色?

I have an adjacency matrix of a bipartite graph (of 1's and 0's) and bi-clusters (array of arrays of rows and columns) for this matrix. How do I set different colours for elements (only 1's) in adjacency matrix which belong to different clusters with matplotlib matshow?

import numpy as np
import matplotlib.pyplot as plt

a_matrix = np.array([[0, 0, 1, 0, 1], [0, 0, 0, 1, 0], [0, 0, 1, 1, 1], [1, 1, 0, 0, 0], [0, 1, 0, 0 ,0]])
cluster_1 = np.array([[1, 2, 3], [3, 4, 5]])
cluster_2 = np.array([[4, 5], [1, 2]])

# plot matrix with one colour
plt.matshow(a_matrix, cmap='Greys', interpolation='nearest')

邻接矩阵,双簇和二部图:

推荐答案

一种方法可能是制作矩阵的副本,然后将不同的值赋予您标识的集群.

One approach might be to make a copy of your matrix and then give distinct values to the clusters you identify.

m = a_matrix.copy()     # a copy we can change without altering the orignal
c = cluster_1           # an alias to save typing

# Naked NumPy doesn't seem to have a cartesian product, so roll our own
for i in range(c.shape[1]):
    for j in range(c.shape[1]):
        if m[c[0,i]-1,c[1,j]-1]:
            m[c[0,i]-1,c[1,j]-1] = 2

plt.matshow(m, cmap='jet', interpolation='nearest')
plt.show()

对于更多群集,请遍历以上内容,为每个群集设置不同的值(并可能选择或定义更好的色彩图).我敢肯定,笛卡尔积也有更有效的实现...

For more clusters, loop over the above, setting a distinct value for each cluster (and maybe choose or define a better colormap). I'm sure there are more efficient implementations of the cartesian product as well...

这篇关于如何在matplotlib matshow中更改矩阵某些元素的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆