.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "gallery/network_science/plot_traveling_salesman.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_traveling_salesman.py: Traveling salesman ================== This example from networkx demonstrates simple styling of nodes and edges. .. GENERATED FROM PYTHON SOURCE LINES 7-74 .. image-sg:: /gallery/network_science/images/sphx_glr_plot_traveling_salesman_001.png :alt: plot traveling salesman :srcset: /gallery/network_science/images/sphx_glr_plot_traveling_salesman_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none The route of the traveller is: [0, 4, 19, 12, 2, 7, 10, 18, 5, 13, 6, 11, 3, 16, 17, 15, 14, 8, 9, 1, 0] | .. code-block:: Python import matplotlib.pyplot as plt import networkx as nx import networkx.algorithms.approximation as nx_app import math import iplotx as ipx G = nx.random_geometric_graph(20, radius=0.4, seed=3) pos = nx.get_node_attributes(G, "pos") # Depot should be at (0,0) pos[0] = (0.5, 0.5) H = G.copy() # Calculating the distances between the nodes as edge's weight. for i in range(len(pos)): for j in range(i + 1, len(pos)): dist = math.hypot(pos[i][0] - pos[j][0], pos[i][1] - pos[j][1]) dist = dist G.add_edge(i, j, weight=dist) cycle = nx_app.christofides(G, weight="weight") edge_list = list(nx.utils.pairwise(cycle)) edge_color = { tuple(e): "red" if e in edge_list or e[::-1] in edge_list else "none" for e in G.edges() } nx.set_edge_attributes(G, edge_color, "color") ipx.plot( H, layout=pos, style={ "edge": { "color": "blue", "linewidth": 1, }, "vertex": { "facecolor": "none", "edgecolor": "none", }, }, ) ipx.plot( G, ax=plt.gca(), layout=pos, vertex_labels=True, style={ "edge": { "color": G.edges.data("color"), "linewidth": 3, }, "vertex": { "size": 20, "facecolor": "steelblue", "edgecolor": "none", "label": { "color": "black", }, }, }, ) print("The route of the traveller is:", cycle) .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.255 seconds) .. _sphx_glr_download_gallery_network_science_plot_traveling_salesman.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_traveling_salesman.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_traveling_salesman.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_traveling_salesman.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_