Plotting the degree distribution of a graph using nx.degree_histogram

Amit Mek picture Amit Mek · Dec 28, 2018 · Viewed 17.2k times · Source

I've tried to use the following code to plot the degree distribution of the 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])

But then I realized that this is not the proper way to do it and so I changed it to:

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()

But this gives me an empty plot with with no data in it.

Answer

user10605163 picture user10605163 · Dec 29, 2018

One way of printing the (in- plus out-)degree histogram with test code:

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))

The number of bins for the histogram can be adjusted by adding a second parameter to plt.hist.