我将假设“绘制邻接矩阵”是指绘制一个 numpy 矩阵,而“点”是指矩阵中的元素。
在下面的代码中,我使用您的matrix 和network_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)
这是输出(我将绘制的矩阵)。请注意,根据您的matrix 和network_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()
最终的邻接矩阵: