如何在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...