【问题标题】:How to change colour of certain elements of a matrix in matplotlib matshow?如何在matplotlib matshow中更改矩阵某些元素的颜色?
【发布时间】:2016-05-24 13:48:00
【问题描述】:

对于这个矩阵,我有一个二分图(1 和 0)和双簇(行和列数组的数组)的邻接矩阵。如何使用matplotlib matshow为属于不同簇的邻接矩阵中的元素(只有1个)设置不同的颜色?

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

邻接矩阵、双聚类和二部图:

【问题讨论】:

    标签: python numpy matrix matplotlib


    【解决方案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()
    

    对于更多的集群,循环上面的,为每个集群设置一个不同的值(并且可能选择或定义一个更好的颜色图)。我敢肯定笛卡尔积还有更有效的实现......

    【讨论】:

    • 感谢您的回答!有用。顺便说一句,我在 sklearn 中找到了笛卡尔积的实现。 sklearn.utils.extmath import cartesian
    猜你喜欢
    • 2013-02-26
    • 2017-08-18
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 2019-11-09
    • 2015-12-29
    相关资源
    最近更新 更多