【问题标题】:python - plot adjacency matrix with colored nodes according to node classpython - 根据节点类绘制带有彩色节点的邻接矩阵
【发布时间】:2017-01-18 20:03:16
【问题描述】:

我想绘制一个邻接矩阵,其中点的颜色与节点类一致。

如果 x 和 y 节点之间存在边:

  • 如果两个节点都属于 0 类 => 红色
  • 如果两个节点都属于 1 类 => 颜色为蓝色
  • 如果两个节点都属于 2 类 => 颜色为绿色
  • else => 灰色

我有一个来自 networkx 的邻接矩阵(作为 nx) 让我们说:

matrix = np.array([[1 0 0 0 0],[1 0 1 0 0],[1 1 0 1 0],[1 0 0 0 1],[1 0 1 0 0]])

我还有一个名为“network_num”的属性,用于将每个节点分类为 0 或 1 或 2。

  • 节点 0 -> 0
  • 节点 1 -> 0
  • 节点 2 -> 1
  • 节点 3 -> 1
  • 节点 4 -> 2

    network_num = {0:0,1:0,2:1,3:1,4:2}

【问题讨论】:

标签: python matplotlib networkx


【解决方案1】:

我将假设“绘制邻接矩阵”是指绘制一个 numpy 矩阵,而“点”是指矩阵中的元素。

在下面的代码中,我使用您的matrixnetwork_num 创建我的drawn_matrix(将被绘制)。 在检查边缘是否存在后,我为您的“红色”案例分配 drawn_matrix 0.25,为您的“蓝色”案例分配 0.5,为您的“绿色”案例分配 1.0(有关以下数字的更多信息)。 请注意,我将无边(matrix 中的 0)标记为灰色。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

# Graph data
network_num = {0: 0, 1: 0, 2: 1, 3: 1, 4: 2}
matrix = np.array([[1, 0, 0, 0, 0],
                   [1, 0, 1, 0, 0],
                   [1, 1, 0, 1, 0],
                   [1, 0, 0, 0, 1],
                   [1, 0, 1, 0, 0]])

drawn_matrix = np.zeros((5, 5))

# Iterate 5x5 matrix
for row in range(5):
    for col in range(5):
        # check if edge exists
        if matrix[row][col] == 1:
            # red
            if network_num[row] == 0 and network_num[col] == 0:
                drawn_matrix[row][col] = 0.25
            # blue
            elif network_num[row] == 1 and network_num[col] == 1:
                drawn_matrix[row][col] = 0.5
            # green
            elif network_num[row] == 2 and network_num[col] == 2:
                drawn_matrix[row][col] = 1.0
            # gray
            else:
                drawn_matrix[row][col] = 0.0
        else:
            drawn_matrix[row][col] = 0.0  # no edge is marked as gray

print("Matrix with color info:")
print(drawn_matrix)

这是输出(我将绘制的矩阵)。请注意,根据您的matrixnetwork_num,图中不会出现绿色。

Matrix with color info:
[[ 0.25  0.    0.    0.    0.  ]
 [ 0.25  0.    0.    0.    0.  ]
 [ 0.    0.    0.    0.5   0.  ]
 [ 0.    0.    0.    0.    0.  ]
 [ 0.    0.    0.    0.    0.  ]]

现在是实际情节。在这里,我发现 this anwser 非常有帮助。 在代码中,我使用以下颜色定义了一个自定义颜色图:灰色、红色、蓝色和绿色。请注意,rvb 中的数值与我之前发布的代码中的值匹配。

def make_colormap(seq):
    """Return a LinearSegmentedColormap
    seq: a sequence of floats and RGB-tuples. The floats should be increasing
    and in the interval (0,1).
    """
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)

c = mcolors.ColorConverter().to_rgb
rvb = make_colormap(
    [c('gray'), c('red'), 0.25, c('red'), c('blue'), 0.5, c('blue'), c('green'), 0.75, c('green')])

plt.matshow(drawn_matrix, vmin=0.0, vmax=1.0, cmap=rvb)
plt.show()

最终的邻接矩阵:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-25
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多