Python: 如何根据节点的度数给网络节点着色?

Python: how to color the nodes of a network according to their degree?

我有一个由 10000 个节点组成的无标度网络,但边缘的纹理和节点的数量让它变得过于复杂而无法理解。 我希望能够直观地定位连接度最高的节点。

如何根据节点的度数 k 为节点着色? 具体来说,我想根据预先指定的范围为它们着色,例如:

下面是我获取网络的方法:

import networkx as nx
import matplotlib.pyplot as plt
n = 10000  # Number of nodes
m = 3  # Number of initial links
seed = 500
G = nx.barabasi_albert_graph(n, m, seed)
ncols = 100
pos = {i : (i % ncols, (n-i-1)//ncols) for i in G.nodes()}
fig, ax = plt.subplots()
nx.draw(G, pos, with_labels=False, ax=ax, node_size=10)
degrees=G.degree() #Dict with Node ID, Degree
sum_of_degrees=sum(degrees.values()) #Sum of degrees
avg_degree_unaltered=sum_of_degrees/10000 #The average degree <k>
short_path=nx.average_shortest_path_length(G)
print('seed: '+str(seed)+', short path: '+str(round(short_path,3))+', log(N)=4')
#Plot the graph
plt.xlim(-20,120,10)
plt.xticks(numpy.arange(-20, 130, 20.0))
plt.ylim(120,-20,10) 
plt.yticks(numpy.arange(-20, 130, 20.0))
plt.axis('on')
title_string=('Scale-Free Network') 
subtitle_string=('100x100'+' = '+str(n)+' nodes')
plt.suptitle(title_string, y=0.99, fontsize=17)
plt.title(subtitle_string, fontsize=8)
plt.show()

这是没有应用差异着色的结果。 PS: ID为0的初始节点在左上角。

我只做 3 种颜色:如果 k<10,则为绿色;如果 10<=k <20 则为蓝色;橙色如果 20<=k

greennodes = [node for node in G.nodes_iter() if G.degree(node)<10]
bluenodes = [node for node in G.nodes_iter() if 10<=G.degree(node)<20]
orangenodes = [node for node in G.nodes_iter() if 20<= G.degree(node)]

pos = {i : (i % ncols, (n-i-1)//ncols) for i in G.nodes()}
fig, ax = plt.subplots()
nx.draw_networkx_edges(G, pos) #draw edges first
nx.draw_networkx_nodes(G, pos, with_labels=False, ax=ax, node_size=10, nodelist = 
greennodes, node_color = 'g') #draw green nodes
nx.draw_networkx_nodes(G, pos, with_labels=False, ax=ax, node_size=10, nodelist = 
bluenodes, node_color = 'g') #draw blue nodes
nx.draw_networkx_nodes(G, pos, with_labels=False, ax=ax, node_size=10, nodelist = 
orangenodes, node_color = 'g') #draw orange nodes

可能是一种更好的方法(使用 itertools?)避免必须循环遍历节点 3 次以收集所有节点。

在引擎盖下,这只是作为一个 matplotlib scatter 图实现的,networkx API 让你传递许多 options through

import numpy as np
import matplotlib.colors as mcolors
import networkx as nx
import matplotlib.pyplot as plt
n = 10000  # Number of nodes
m = 3  # Number of initial links
seed = 500
G = nx.barabasi_albert_graph(n, m, seed)

ncols = 100
pos = {i : (i % ncols, (n-i-1)//ncols) for i in G.nodes()}

fig, ax = plt.subplots()
degrees = G.degree() #Dict with Node ID, Degree
nodes = G.nodes()
n_color = np.asarray([degrees[n] for n in nodes])
sc = nx.draw_networkx_nodes(G, pos, nodelist=nodes, node_color=n_color, cmap='viridis',
                            with_labels=False, ax=ax, node_size=n_color)
# use a log-norm, do not see how to pass this through nx API
# just set it after-the-fact
sc.set_norm(mcolors.LogNorm())
fig.colorbar(sc)

这会根据度数缩放颜色和大小。

这可以使用 BoundryNorm 和离散颜色图将节点分割成条带进行扩展。