简体   繁体   中英

Plot degree distribution in log-log scale

I have a graph in networkx and im trying to plot the degree distribution. So i wrote the following code:

g = nx.read_edgelist('graph.txt', create_using= nx.Graph(), nodetype=int)

print(nx.info(g))
numOfNodes = []
for i in range(0, g.number_of_nodes()):
    numOfNodes.append(i)

s = sorted(g.degree, key=lambda x: x[1], reverse=True)
degrees = sorted([x[0] for x in s])
frequency = sorted([x[1] for x in s])
plt.loglog(numOfNodes, degrees)
plt.xlabel("Degree")
plt.ylabel("No. of nodes (Frequency)")
plt.title("Degree distribution")
plt.show()

I expected to get a diagram like this:

在此处输入图像描述

but im getting something much different: 在此处输入图像描述

What is wrong with my plot of degree distribution? I can't find what im doing wrong.

These are the two ways I know to obtain the degree distribution:

1. Using the networkX degree_histogram function( docs ):

Here's an example on how to use:

def plot_degree_histogram(g, normalized=True):
    print("Creating histogram...")
    aux_y = nx.degree_histogram(g)
    
    aux_x = np.arange(0,len(aux_y)).tolist()
    
    n_nodes = g.number_of_nodes()
    
    if normalized:
        for i in range(len(aux_y)):
            aux_y[i] = aux_y[i]/n_nodes
    
    return aux_x, aux_y

2. In case you are using weights, follow this example from networkX documentation:

def plot_degree_histogram(g, normalized=True, weight=None):
    
    degree_sequence = sorted([d for n, d in g.degree(weight=weight)], reverse=True)  # degree sequence
    degreeCount = collections.Counter(degree_sequence)
    aux_x, aux_y = zip(*degreeCount.items())

    n_nodes = g.number_of_nodes()
    aux_y = list(aux_y)
    if normalized:
        for i in range(len(aux_y)):
            aux_y[i] = aux_y[i]/n_nodes
    
    return aux_x, aux_y

Plotting

Simple as:

plt.title('\nDistribution Of Node Linkages (log-log scale)')
plt.xlabel('Degree\n(log scale)')
plt.ylabel('Number of Nodes\n(log scale)')
plt.xscale("log")
plt.yscale("log")
plt.plot(aux_x, aux_y, 'o')

About you implementation:

I believe that your degrees list is valid. However numOfNodes is not what you are looking for, ie not the counting of nodes of each degree.
Hope the above solutions help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM