首页 > 解决方案 > python-用networkx获取网络节点的度数

问题描述

我想用 NetworkX 函数得到所有节点的度数分布图,然后画一个箱线图。

但情节未显示,并有以下错误:

x = all_degrees.count(i)

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

如何解决这个问题呢?

mac OS 10.14.5 (18F132) 蟒蛇 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)

标签: pythonnetworkingnodesnetworkx

解决方案


Your main problem is that all_degrees is DegreeView iterable -- not a list -- so it doesn't have the built-in count method. (In addition, unique_degrees is not actually going to be unique, since you can have the same value appear multiple times.)

Fixing the main issue

I think the simplest way to fix your issue is to redefine all_degrees like so (and update unique_degrees accordingly):

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

This will yield the following plot (note that it is just a line plot): degrees plot

Getting the boxplot

You can also take advantage of the matplotlib.pyplot.boxplot to do all the heavy lifting for you. Then, all you need to do in plot_deg_dist is get the list of all degrees and call the boxplot function:

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

degrees box


推荐阅读