如何在matplotlib matshow中更改矩阵的某些元素的颜色?

时间:2016-02-13 11:04:33

标签: python numpy matrix matplotlib

我有一个二元图的邻接矩阵(1&0; s和0&#s; s)和bi-clusters(行和列数组)这个矩阵的邻接矩阵。如何使用matplotlib matshow为邻接矩阵中的元素(仅1' s)设置不同的颜色?

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

邻接矩阵,双群集和二分图:

adjacency matrix, bi-clusters, and a bipartite graph

1 个答案:

答案 0 :(得分:1)

一种方法可能是制作矩阵的副本,然后为您识别的群集提供不同的值。

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

enter image description here

对于更多聚类,循环上面的内容,为每个聚类设置一个不同的值(并且可以选择或定义更好的颜色图)。我确信笛卡尔积的实现也更有效......