我有一个涉及图形的可视化问题。我有
顺便说一句,我不是在寻找枢纽/集群,我知道哪些节点在哪个网络中,我只是试图找到一种更整洁的可视化方式。有没有什么简单的方法可以做到这一点?例如,高级弹簧布局,我可以指定一些节点应该一起显示,而不考虑边缘权重/弹簧力?
N
个节点,它们属于某些M
个网络。这些节点可以具有网络内边缘(在同一网络中)和网络间边缘(从一个网络中的节点到另一个网络中的节点)。
当我在networkx
中可视化图形时,我正在寻找一种将网络放置/聚类在一起的方法,以便我可以轻松地识别网络内部/外部的连接。因此,理想情况下,所有蓝色节点将作为网络聚集在一起(没有特定顺序)。同样适用于橙色或绿色节点。顺便说一句,我不是在寻找枢纽/集群,我知道哪些节点在哪个网络中,我只是试图找到一种更整洁的可视化方式。有没有什么简单的方法可以做到这一点?例如,高级弹簧布局,我可以指定一些节点应该一起显示,而不考虑边缘权重/弹簧力?
最小工作生成器
import string, random
import networkx as nx
import matplotlib.pyplot as plt
from scipy.sparse import random as sparse_random
# Random string generator
def rand_string(size=6, chars=string.ascii_uppercase):
return ''.join(random.choice(chars) for _ in range(size))
# Set up a nodes and networks randomly
nodes = [rand_string() for _ in range(30)]
networks = [rand_string() for _ in range(5)]
networks_list = networks*6
random.shuffle(networks_list)
# Define what nodes belong to what network and what their color should be
node_network_map = dict(zip(nodes, networks_list))
colors = ['green', 'royalblue', 'red', 'orange', 'cyan']
color_map = dict(zip(networks, colors))
graph = nx.Graph()
graph.add_nodes_from(nodes)
nodes_by_color = {val: [node for node in graph if color_map[node_network_map[node]] == val]
for val in colors}
# Take random sparse matrix as adjacency matrix
mat = sparse_random(30, 30, density=0.3).todense()
for row, row_val in enumerate(nodes):
for col, col_val in enumerate(nodes):
if col > row and mat[row, col] != 0.0: # Stick to upper half triangle, mat is not symmetric
graph.add_edge(row_val, col_val, weight=mat[row, col])
# Choose a layout to visualize graph
pos = nx.spring_layout(graph)
edges = graph.edges()
# Get the edge weights and normalize them
weights = [abs(graph[u][v]['weight']) for u, v in edges]
weights_n = [5*float(i)/max(weights) for i in weights] # Change 5 to control thickness
# First draw the nodes
plt.figure()
for color, node_names in nodes_by_color.items():
nx.draw_networkx_nodes(graph, pos=pos, nodelist=node_names, node_color=color)
# Then draw edges with thickness defined by weights_n
nx.draw_networkx_edges(graph, pos=pos, width=weights_n)
nx.draw_networkx_labels(graph, pos=pos)
plt.show()