{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Degree Analysis\n\nThis example shows several ways to visualize the distribution of the degree of\nnodes with two common techniques: a *degree-rank plot* and a\n*degree histogram*.\n\nIn this example, a random Graph is generated with 100 nodes. The degree of\neach node is determined, and a figure is generated showing three things:\n1. The subgraph of connected components\n2. The degree-rank plot for the Graph, and\n3. The degree histogram\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nG = nx.gnp_random_graph(100, 0.02, seed=10374196)\n\ndegree_sequence = sorted((d for n, d in G.degree()), reverse=True)\ndmax = max(degree_sequence)\n\nfig = plt.figure(\"Degree of a random graph\", figsize=(8, 8))\n# Create a gridspec for adding subplots of different sizes\naxgrid = fig.add_gridspec(5, 4)\n\nax0 = fig.add_subplot(axgrid[0:3, :])\nGcc = G.subgraph(sorted(nx.connected_components(G), key=len, reverse=True)[0])\npos = nx.spring_layout(Gcc, seed=10396953)\nnx.draw_networkx_nodes(Gcc, pos, ax=ax0, node_size=20)\nnx.draw_networkx_edges(Gcc, pos, ax=ax0, alpha=0.4)\nax0.set_title(\"Connected components of G\")\nax0.set_axis_off()\n\nax1 = fig.add_subplot(axgrid[3:, :2])\nax1.plot(degree_sequence, \"b-\", marker=\"o\")\nax1.set_title(\"Degree Rank Plot\")\nax1.set_ylabel(\"Degree\")\nax1.set_xlabel(\"Rank\")\n\nax2 = fig.add_subplot(axgrid[3:, 2:])\nax2.bar(*np.unique(degree_sequence, return_counts=True))\nax2.set_title(\"Degree histogram\")\nax2.set_xlabel(\"Degree\")\nax2.set_ylabel(\"# of Nodes\")\n\nfig.tight_layout()\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.7"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Generated by dwww version 1.16 on Wed Apr 8 11:22:55 CEST 2026.