Python - 使用定向链接连接节点

Python - connect nodes with directed-links

我是运行车辆路径优化模型。下面是位置坐标(节点)列表,以及显示要访问的位置序列的优化输出。我想知道如何创建如下图来可视化我的输出。

locations = \
        [(4, 4), # depot
         (2, 0), (8, 0), # row 0
         (0, 1), (1, 1),
         (5, 2), (7, 2),
         (3, 3), (6, 3),
         (5, 5), (8, 5),
         (1, 6), (2, 6),
         (3, 7), (6, 7),
         (0, 8), (7, 8)]

[Route for vehicle 0:
 0 ->  8 ->  6 ->  2 ->  5 ->  0
Distance of the route 0: 1552.0

Route for vehicle 1:
 0 ->  7 ->  1 ->  4 ->  3 ->  0
Distance of the route 1: 1552.0

Route for vehicle 2:
 0 ->  9 ->  10 ->  16 ->  14 ->  0
Distance of the route 2: 1552.0

Route for vehicle 3:
 0 ->  12 ->  11 ->  15 ->  13 ->  0
Distance of the route 3: 1552.0][1]

我认为绘制网络的最佳工具是库 networkx。 在下面的代码中,为了 select 正确地 select 颜色节点,我只用了几个 triks 就重现了你示例的 1/2。

import networkx as nx

locations = {
    0:(4,4),
    1:(2,8),
    2:(8,8),
    3:(0,7),
    4:(1,7),
    5:(5,6),
    6:(7,6),
    7:(3,6),
    8:(6,5),
}

edges = [
    (0, 8, {'vehicle': '0'}),
    (8, 6, {'vehicle': '0'}),
    (6, 2, {'vehicle': '0'}),
    (2, 5, {'vehicle': '0'}),
    (5, 0, {'vehicle': '0'}),
    (0, 7, {'vehicle': '1'}),
    (7, 1, {'vehicle': '1'}),
    (1, 4, {'vehicle': '1'}),
    (4, 3, {'vehicle': '1'}),
    (3, 0, {'vehicle': '1'}),
]

G=nx.DiGraph()

G.add_edges_from(edges)

plt.figure(figsize=(15,10))

#vehicle 0
temp = [e for e in edges if e[2]['vehicle'] == '0'] #temporary list that filters the path of vehicle 0
nx.draw_networkx_nodes(G, locations, nodelist=[x[0] for x in temp], node_color='b')
nx.draw_networkx_edges(G, locations, edgelist=temp,
                       width=2, edge_color='b', style='dashed')

#vehicle 1
temp = [e for e in edges if e[2]['vehicle'] == '1']
nx.draw_networkx_nodes(G, locations, nodelist=[x[0] for x in temp], node_color='r')
nx.draw_networkx_edges(G, locations, edgelist=temp,
                       width=2, edge_color='r', style='dashed')

#let's color the node 0 in black
nx.draw_networkx_nodes(G, locations, nodelist=[0], node_color='k')

# labels
nx.draw_networkx_labels(G, locations, font_color='w', font_size=12, font_family='sans-serif')

#print out the graph
plt.axis('off')
plt.show()

这是输出: