Ami*_*Mek 6 python directed-graph matplotlib histogram networkx
我尝试使用以下代码来绘制 的度分布networkx.DiGraph G:
def plot_degree_In(G):
in_degrees = G.in_degree()
in_degrees=dict(in_degrees)
in_values = sorted(set(in_degrees.values()))
in_hist = [list(in_degrees.values()).count(x) for x in in_values]
plt.figure()
plt.grid(False)
plt.loglog(in_values, in_hist, 'r.')
#plt.loglog(out_values, out_hist, 'b.')
#plt.legend(['In-degree', 'Out-degree'])
plt.xlabel('k')
plt.ylabel('p(k)')
plt.title('Degree Distribution')
plt.xlim([0, 2*100**1])
Run Code Online (Sandbox Code Playgroud)
但后来我意识到这不是正确的做法,所以我将其更改为:
def plot_degree_dist(G):
degree_hist = nx.degree_histogram(G)
degree_hist = np.array(degree_hist, dtype=float)
degree_prob = degree_hist/G.number_of_nodes()
plt.loglog(np.arange(degree_prob.shape[0]),degree_prob,'b.')
plt.xlabel('k')
plt.ylabel('p(k)')
plt.title('Degree Distribution')
plt.show()
Run Code Online (Sandbox Code Playgroud)
但这给了我一个没有数据的空图。
yat*_*atu 11
我们可以利用nx.degree_histogram,它返回网络中度数频率的列表,其中度数值是列表中相应的索引。然而,该函数仅针对无向图实现。我将首先说明如何在无向图的情况下使用它,然后展示一个有向图的示例,我们可以看到如何通过稍微调整 来获得度分布nx.degree_histogram。
对于有向图,我们可以使用nx.degree_histogram. 下面是使用随机图生成器的示例nx.barabasi_albert_graph。
x通常,在绘制度分布时,会取和轴的对数y,这有助于查看 networkx 是否是无标度的(度分布遵循幂律的网络),因此我们可以使用 matplotlibplt.loglog来实现:
m=3
G = nx.barabasi_albert_graph(1000, m)
degree_freq = nx.degree_histogram(G)
degrees = range(len(degree_freq))
plt.figure(figsize=(12, 8))
plt.loglog(degrees[m:], degree_freq[m:],'go-')
plt.xlabel('Degree')
plt.ylabel('Frequency')
Run Code Online (Sandbox Code Playgroud)
对于有向图,我们可以稍微修改函数nx.degree_histogram以考虑入度和出度:
def degree_histogram_directed(G, in_degree=False, out_degree=False):
"""Return a list of the frequency of each degree value.
Parameters
----------
G : Networkx graph
A graph
in_degree : bool
out_degree : bool
Returns
-------
hist : list
A list of frequencies of degrees.
The degree values are the index in the list.
Notes
-----
Note: the bins are width one, hence len(list) can be large
(Order(number_of_edges))
"""
nodes = G.nodes()
if in_degree:
in_degree = dict(G.in_degree())
degseq=[in_degree.get(k,0) for k in nodes]
elif out_degree:
out_degree = dict(G.out_degree())
degseq=[out_degree.get(k,0) for k in nodes]
else:
degseq=[v for k, v in G.degree()]
dmax=max(degseq)+1
freq= [ 0 for d in range(dmax) ]
for d in degseq:
freq[d] += 1
return freq
Run Code Online (Sandbox Code Playgroud)
与上面类似,我们可以生成入度或/和出度的图表。这是一个随机比例格力图的示例:
G = nx.scale_free_graph(5000)
in_degree_freq = degree_histogram_directed(G, in_degree=True)
out_degree_freq = degree_histogram_directed(G, out_degree=True)
degrees = range(len(in_degree_freq))
plt.figure(figsize=(12, 8))
plt.loglog(range(len(in_degree_freq)), in_degree_freq, 'go-', label='in-degree')
plt.loglog(range(len(out_degree_freq)), out_degree_freq, 'bo-', label='out-degree')
plt.xlabel('Degree')
plt.ylabel('Frequency')
Run Code Online (Sandbox Code Playgroud)
小智 9
使用测试代码打印(入加出)度直方图的一种方法:
import matplotlib.pyplot as plt
import networkx as nx
def plot_degree_dist(G):
degrees = [G.degree(n) for n in G.nodes()]
plt.hist(degrees)
plt.show()
plot_degree_dist(nx.gnp_random_graph(100, 0.5, directed=True))
Run Code Online (Sandbox Code Playgroud)
可以通过向 中添加第二个参数来调整直方图的 bin 数量plt.hist。
小智 5
今天遇到了同样的问题。一些典型的学位分布图(示例)不会对学位计数进行分类。相反,他们将每个度数的计数分散在双对数图上。
这就是我的想法。由于在常见的直方图函数中关闭分箱似乎很困难,因此我决定选择一个标准Counter来完成这项工作。
degrees预计在节点度数上是可迭代的(由 networkx 返回)。
给出Counter.items()[(度数,计数)]对的列表。将列表解压缩到 x 和 y 后,我们可以准备具有对数刻度的轴,并绘制散点图。
from collections import Counter
from operator import itemgetter
import matplotlib.pyplot as plt
# G = some networkx graph
degrees = G.in_degree()
degree_counts = Counter(degrees)
x, y = zip(*degree_counts.items())
plt.figure(1)
# prep axes
plt.xlabel('degree')
plt.xscale('log')
plt.xlim(1, max(x))
plt.ylabel('frequency')
plt.yscale('log')
plt.ylim(1, max(y))
# do plot
plt.scatter(x, y, marker='.')
plt.show()
Run Code Online (Sandbox Code Playgroud)
我手动剪辑xlim,ylim因为自动缩放会使点在对数刻度中丢失一些。小点标记效果最好。
希望能帮助到你
编辑:这篇文章的早期版本包括对度数对进行排序,这对于具有明确定义的 x 和 y 的散点图来说当然不是必需的。查看示例图片:
