{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Directed Graph\n\nDraw a graph with directed edges using a colormap and different node sizes.\n\nEdges have different colors and alphas (opacity). Drawn using matplotlib.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\nseed = 13648 # Seed random number generators for reproducibility\nG = nx.random_k_out_graph(10, 3, 0.5, seed=seed)\npos = nx.spring_layout(G, seed=seed)\n\nnode_sizes = [3 + 10 * i for i in range(len(G))]\nM = G.number_of_edges()\nedge_colors = range(2, M + 2)\nedge_alphas = [(5 + i) / (M + 4) for i in range(M)]\ncmap = plt.cm.plasma\n\nnodes = nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color=\"indigo\")\nedges = nx.draw_networkx_edges(\n G,\n pos,\n node_size=node_sizes,\n arrowstyle=\"->\",\n arrowsize=10,\n edge_color=edge_colors,\n edge_cmap=cmap,\n width=2,\n)\n# set alpha value for each edge\nfor i in range(M):\n edges[i].set_alpha(edge_alphas[i])\n\npc = mpl.collections.PatchCollection(edges, cmap=cmap)\npc.set_array(edge_colors)\n\nax = plt.gca()\nax.set_axis_off()\nplt.colorbar(pc, ax=ax)\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:56:15 CEST 2026.