Networkx常用操作記録


地下鉄データ分析
g.remove_node()#    
lst = list(nx.connected_component_subgraphs(G))#     ,      
print(nx.number_of_nodes(G))#   
print(nx.number_of_edges(G))#  
print(nx.average_shortest_path_length(G)) #        
print(nx.average_clustering(G))#      
degree = nx.degree_histogram(G)#   --  list
print(degree)
print(nx.diameter(G))#    
def ave(degree):#     
    s_um = 0
    for i in range(len(degree)):
        s_um =s_um+i*degree[i]
    return s_um/nx.number_of_nodes(G)
ave(degree)

絵をかく
x = list(range(len(degree)))
y = [i for i in degree]
plt.bar(x, y, align='center')#plot、loglog
plt.ylim(0, 300)
plt.title('Distribution of Nodes')
plt.xlabel('Degree')
plt.ylabel('Number of Nodes')
for a, b in zip(x,y):
    plt.text(a, b+2,'%.0f' % b, ha='center')
#plt.savefig("degree.png")
plt.show()

最短パス確率分布の計算
dis = nx.all_pairs_shortest_path_length(G)#        
def ss():
    for key in dis.keys():
        yield dis[key].values()
freq = [0 for i in range(45)]
for i in ss():
    for j in i:
        freq[j] +=1
print(freq)#freq        list
#      
y_=[]
for i in range(len(freq)):
    j = sum(freq[:i+1])
    y_.append(j)
y_#      ---list