Skip to content

Commit 5d16090

Browse files
authored
Gallery: Improve plot_degree_sequence example (networkx#8601)
* More context for initial print. * Remove unnecessary comments, more context for print. * Replace bespoke hist with degree_histogram.
1 parent 194fded commit 5d16090

1 file changed

Lines changed: 14 additions & 18 deletions

File tree

examples/graph/plot_degree_sequence.py

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,31 +6,27 @@
66
Random graph from given degree sequence.
77
"""
88

9+
from pprint import pprint
910
import matplotlib.pyplot as plt
1011
import networkx as nx
1112

1213
# Specify seed for reproducibility
1314
seed = 668273
1415

1516
z = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
16-
print(nx.is_graphical(z))
17-
18-
print("Configuration model")
19-
G = nx.configuration_model(
20-
z, seed=seed
21-
) # configuration model, seed for reproducibility
22-
degree_sequence = [d for n, d in G.degree()] # degree sequence
23-
print(f"Degree sequence {degree_sequence}")
24-
print("Degree histogram")
25-
hist = {}
26-
for d in degree_sequence:
27-
if d in hist:
28-
hist[d] += 1
29-
else:
30-
hist[d] = 1
31-
print("degree #nodes")
32-
for d in hist:
33-
print(f"{d:4} {hist[d]:6}")
17+
print(f"Sequence {z} is a valid degree sequence: {nx.is_graphical(z)}")
18+
19+
G = nx.configuration_model(z, seed=seed)
20+
degree_sequence = [d for _, d in G.degree()]
21+
22+
# The degree sequence for the random graph computed using configuration_model
23+
# should match the degree sequence used to generate it
24+
print(f"Degree sequence of G identical to z: {degree_sequence == z}")
25+
26+
print("\nDegree histogram")
27+
deg_hist = dict(enumerate(nx.degree_histogram(G)))
28+
print("degree: #nodes")
29+
pprint(deg_hist, width=10)
3430

3531
pos = nx.spring_layout(G, seed=seed) # Seed layout for reproducibility
3632
nx.draw(G, pos=pos)

0 commit comments

Comments
 (0)