1

我正在努力为我在网上找到的 Facebook 数据绘制幂律图。我正在使用 Networkx,并且我已经找到了如何绘制学位直方图和学位等级的方法。我遇到的问题是我希望 y 轴是一个概率,所以我假设我需要总结每个 y 值并除以节点总数?谁能帮我做到这一点?一旦我得到了这个,我想画一个对数对数图,看看我是否能得到一条直线。如果有人可以提供帮助,我将不胜感激!这是我的代码:

import collections 
import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms import community
import math
import pylab as plt

g = nx.read_edgelist("/Users/Michael/Desktop/anaconda3/facebook_combined.txt","r")
nx.info(g)

degree_sequence = sorted([d for n, d in g.degree()], reverse=True)
degreeCount = collections.Counter(degree_sequence)
deg, cnt = zip(*degreeCount.items())
fig, ax = plt.subplots()
plt.bar(deg, cnt, width=0.80, color='b')
plt.title("Degree Histogram for Facebook Data")
plt.ylabel("Count")
plt.xlabel("Degree")
ax.set_xticks([d + 0.4 for d in deg])
ax.set_xticklabels(deg)
plt.show()

plt.loglog(degree_sequence, 'b-', marker='o')
plt.title("Degree rank plot")
plt.ylabel("Degree")
plt.xlabel("Rank")
plt.show()
4

1 回答 1

1

您似乎走在正确的轨道上,但一些简化可能会对您有所帮助。下面的代码仅使用 2 个库。

在不访问您的图表的情况下,我们可以使用一些图表生成器。我在这里选择了 2 种质量不同的类型,并特意选择了不同的大小,以便需要对直方图进行归一化。

import networkx as nx
import matplotlib.pyplot as plt

g1 = nx.scale_free_graph(1000, ) 
g2 = nx.watts_strogatz_graph(2000, 6, p=0.8) 

# we don't need to sort the values since the histogram will handle it for us
deg_g1 = nx.degree(g1).values()
deg_g2 = nx.degree(g2).values()
# there are smarter ways to choose bin locations, but since
# degrees must be discrete, we can be lazy...
max_degree = max(deg_g1 + deg_g2)

# plot different styles to see both
fig = plt.figure()
ax = fig.add_subplot(111)
ax.hist(deg_g1, bins=xrange(0, max_degree), density=True, histtype='bar', rwidth=0.8)
ax.hist(deg_g2, bins=xrange(0, max_degree), density=True, histtype='step', lw=3) 

# setup the axes to be log/log scaled
ax.set_yscale('log')
ax.set_xscale('log')
ax.set_xlabel('degree')
ax.set_ylabel('relative density')
ax.legend()

plt.show()

这会产生一个像这样的输出图(g1,g2 都是随机的,所以不会相同):

度分布

在这里,我们可以看到g1度数分布有一个近似直线衰减 - 正如对数对数轴上的无标度分布所预期的那样。相反,g2没有无标度度分布。

更正式地说,您可以查看 Aaron Clauset 的工具箱:http ://tuvalu.santafe.edu/~aaronc/powerlaws/ ,它实现了模型拟合和幂律分布的统计测试。

于 2018-03-27T14:17:57.347 回答