簡體   English   中英

python-使用networkx獲取網絡節點的程度

[英]python-get the degree of network nodes with networkx

我想使用NetworkX函數獲取所有節點的度數分布圖,然后繪制一個箱線圖。

但是該圖未顯示,並且下面有錯誤:

x = all_degrees.count(i)

AttributeError: 'DegreeView' object has no attribute 'count'

如何解決這個問題呢?

mac OS 10.14.5(18F132)python 3.7

import networkx as nx
import matplotlib.pyplot as plt

def plot_deg_dist(G):
    all_degrees = nx.degree(G)

    unique_degrees = [v for k, v in all_degrees]
    count_of_degrees = []

    for i in unique_degrees:
        x = all_degrees.count(i)
        count_of_degrees.append(x)

    plt.plot(unique_degrees, count_of_degrees)
    plt.show()

G = nx.read_gml("/Users/kate/Desktop/karate_club/karate.gml")


plot_deg_dist(G)

您的主要問題是all_degrees是可迭代的DegreeView - 而不是 list -因此它沒有內置的count方法。 (此外, unique_degrees實際上不會是唯一的,因為您可以多次顯示相同的值。)

解決主要問題

我認為解決問題的最簡單方法是像這樣重新定義all_degrees (並相應地更新unique_degrees ):

all_degrees = [ v for _, v in nx.degree(G) ]
unique_degrees = sorted(set(all_degrees))

這將產生以下圖(請注意,這只是一個線圖): 度圖

獲取箱線圖

您還可以利用matplotlib.pyplot.boxplot為您完成所有繁重的工作。 然后,您需要在plot_deg_dist中獲取所有度數的列表並調用boxplot函數:

all_degrees = [ v for _, v in nx.degree(G) ]
plt.boxplot(all_degrees)
plt.show()

度盒

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM