.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "gallery/network_science/plot_shortest_path.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_gallery_network_science_plot_shortest_path.py: Shortest path ============= This example from networkx shows how to use edge labels and their rotation. .. GENERATED FROM PYTHON SOURCE LINES 7-56 .. image-sg:: /gallery/network_science/images/sphx_glr_plot_shortest_path_001.png :alt: plot shortest path :srcset: /gallery/network_science/images/sphx_glr_plot_shortest_path_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none [] | .. code-block:: Python import networkx as nx import matplotlib.pyplot as plt import iplotx as ipx G = nx.Graph() G.add_nodes_from(["A", "B", "C", "D", "E", "F", "G", "H"]) G.add_edge("A", "B", weight=4) G.add_edge("A", "H", weight=8) G.add_edge("B", "C", weight=8) G.add_edge("B", "H", weight=11) G.add_edge("C", "D", weight=7) G.add_edge("C", "F", weight=4) G.add_edge("C", "I", weight=2) G.add_edge("D", "E", weight=9) G.add_edge("D", "F", weight=14) G.add_edge("E", "F", weight=10) G.add_edge("F", "G", weight=2) G.add_edge("G", "H", weight=1) G.add_edge("G", "I", weight=6) G.add_edge("H", "I", weight=7) # Find the shortest path from node A to node E path = nx.shortest_path(G, "A", "E", weight="weight") # Create a list of edges in the shortest path path_edges = list(zip(path, path[1:])) nx.set_node_attributes(G, nx.spring_layout(G, seed=37), "pos") nx.set_edge_attributes( G, { (u, v): { "color": ( "red" if (u, v) in path_edges or tuple(reversed((u, v))) in path_edges else "black" ), "label": d["weight"], } for u, v, d in G.edges(data=True) }, ) fig, ax = plt.subplots() ipx.plot( G, ax=ax, layout="pos", vertex_labels=True, edge_labels=True, ) .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.066 seconds) .. _sphx_glr_download_gallery_network_science_plot_shortest_path.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_shortest_path.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_shortest_path.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_shortest_path.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_