{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Ego Graph\n\nExample using the NetworkX ego_graph() function to return the main egonet of\nthe largest hub in a Barab\u00e1si-Albert network.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from operator import itemgetter\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\n# Create a BA model graph - use seed for reproducibility\nn = 1000\nm = 2\nseed = 20532\nG = nx.barabasi_albert_graph(n, m, seed=seed)\n\n# find node with largest degree\nnode_and_degree = G.degree()\n(largest_hub, degree) = sorted(node_and_degree, key=itemgetter(1))[-1]\n\n# Create ego graph of main hub\nhub_ego = nx.ego_graph(G, largest_hub)\n\n# Draw graph\npos = nx.spring_layout(hub_ego, seed=seed) # Seed layout for reproducibility\nnx.draw(hub_ego, pos, node_color=\"b\", node_size=50, with_labels=False)\n\n# Draw ego as large and red\noptions = {\"node_size\": 300, \"node_color\": \"r\"}\nnx.draw_networkx_nodes(hub_ego, pos, nodelist=[largest_hub], **options)\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 10:58:34 CEST 2026.