python - 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)
解决方案
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):
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()
推荐阅读
- javascript - websocketserver应用程序中的范围问题
- performance - 缓存未使用的节点可以加速链表吗?
- javascript - 从 AWS Lambda 提取检索旧数据
- javascript - 在表单按钮 onclick 后应用 Html 样式更改时不会坚持
- python-3.x - 在 Python 3 中经常调用的函数之外定义一个变量
- mysql - 在 CTE 的递归部分中使用 ROW_NUMBER() 是否有替代方法?
- python - 计算过滤器中 SQLAlchemy 关系的数量
- c++ - 用户将字符串输入字符串向量并对其进行验证
- java - Java:我们可以使用多 HashMap 对结果集进行分组吗
- .net-core - AddHttpClient 配置的 HttpClient.Timeout 被忽略