最近在做的东西需要可视化加权有向图,从前做惯了无脑调包的无权无向图,现在不仅网络指标全部得自己算,网络的可视化也是个大问题,在此写下此博客记录自己的学习过程。
Graph Layout
先看节点布局
这里只是对每种布局有所了解,且由于这里是本人用私有数据得到的加权有向图(节点数30)可视化的,这里就不公布文件了,大家可以随机生成一个邻接矩阵进行可视化操作。
pos = nx.random_layout(G)
pos = nx.circular_layout(G)
pos = nx.shell_layout(G)
pos = nx.spring_layout(G)
pos = nx.spectral_layout(G)
pos = nx.kamada_kawai_layout(G)
pos = nx.spiral_layout(G)
有些因为图不满足而且个人也不感兴趣就不画了。
完整代码
def draw_direcetd_weighted_graph(edges_list, output, target, layer): # checked
r'''
Args:
edges_list: direcetd weighted networks' edges list, a tuple like: (source node, target node, weight)
output: the output of CNN after softmax
target: groundture label
layer: draw which layer
Returns: G
Noted that: this graph nodes strat from 1
'''
plt.figure(layer)
color_list = []
color = ['r', 'b', 'y', 'g', 'purple']
edge_weight = []
# deal with edges' color
for i in range(len(edges_list)):
edge_weight.append(edges_list[i][2])
# deal with nodes' color
for i in range(5):
a = [j + 1 for j, x in enumerate(target) if x == i]
color_list.append(a)
# node 0 to batch_size, like
# [[0, 4, 13, 19, 20, 29], [5, 6, 7, 12, 16, 17], [8, 9, 22, 23, 24, 27], [10, 11, 15, 18, 21, 25], [1, 2, 3, 14, 26, 28]]
G = nx.DiGraph()
G.add_weighted_edges_from(edges_list)
pos = nx.circular_layout(G)
# deal with nodes' label
topk1 = (1, 5)
maxk = max(topk1)
_, pred = output.topk(maxk, 1, True, True)
whole_label = torch.cat((target.unsqueeze(1), pred), 1) # concat true & pred
whole_label = whole_label.cpu().numpy()
for i in range(args.batch_size):
G.nodes[i + 1]['label'] = whole_label[i]
# draw colorful nodes
for i in range(len(color_list)):
nx.draw_networkx_nodes(G, pos, nodelist=color_list[i], node_color=color[i], node_size=100)
# draw colorful edges
edges = nx.draw_networkx_edges(G, pos=pos, arrowstyle='->', edge_color=edge_weight, edge_cmap=plt.cm.Oranges)
pc = mpl.collections.PatchCollection(edges, cmap=plt.cm.Oranges)
plt.colorbar(pc)
# draw colorful labels
node_data = nx.get_node_attributes(G, 'label')
nx.draw_networkx_labels(G, pos, labels=node_data, font_color="brown", font_size=8)
# plt.savefig('graph_save/direcetd_weighted_network_%d.jpg' % layer)
return G
可视化结果(存在问题,标签和节点混在一起了!!!):