Python:如何根据它们的程度为网络的节点着色?

FaC*_*fee 2 python colors matplotlib networkx

我有一个由10000节点组成的无标度网络,但是边缘的纹理和节点的数量使它太复杂而无法理解。我希望能够在视觉上找到连接最紧密的节点。

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

  • 绿色如果1<k<10;
  • 如果淡蓝色11<k<20;
  • 蓝色如果21<k<30;
  • 紫色如果31<k<40;
  • ...

这是我获取网络的方法:

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()
Run Code Online (Sandbox Code Playgroud)

这是不应用差异着色的结果。PS: ID为0的初始节点在左上角。 在此处输入图片说明

tac*_*ell 5

scatter后台,这只是作为matplotlib 图实现的,networkx API使您可以通过

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)
Run Code Online (Sandbox Code Playgroud)

图的示例输出

这将根据程度缩放颜色和大小。

可以使用BoundryNorm离散色图来扩展此范围,以将节点划分为带。