We could make use of nx.degree_histogram
, which returns a list of frequencies of the degrees in the network, where the degree values are the corresponding indices in the list. However, this function is only implemented for undirected graphs. I'll first illustrate how to use it in the case of an undirected graph, and then show an example with a directed graph, were we can see how to obtain the degree distributions by slightly adapting nx.degree_histogram
.
For a directed graph we can make use of nx.degree_histogram
. Bellow is an example using the random graph generator nx.barabasi_albert_graph
.
Normally the logarithm of both x
and y
axes is taken when plotting the degree distribution, this helps seeing if a networkx is scale-free (a network with a degree distribution following a power law), so we can use matplotlib's plt.loglog
for that :
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')
For directed graphs, we could slightly modify the function nx.degree_histogram
to contemplate both in and out degrees:
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
And similarly to above, we could generate a graph for the in-degree or/and the out-degree. Here's an example with a random scale-gree graph:
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')