如何使用python中的networkx在有向(非对称)图中制作两条边(从一个节点开始的1条边和以该节点结束的2nd边)bw两个节点?

问题描述 投票:0回答:1

我有 50 个城市的距离矩阵。 前 10 个城市的样本矩阵如下所示:

0 1 2 3 4 5 6 7 8 9
0 0 信息 1033.836 2954.445 信息 570.7902 信息 5201.642 927.6648 信息
1 信息 0 846.4284 2988.993 1739.0 586.6539 556.8027 4718.087 992.3883 信息
2 1065.751 信息 0 3713.848 2328.803 1293.154 922.5469 5968.72 1660.567 917.3977
3 3093.118 2721.323 3738.992 0 1386.044 2593.299 2926.249 2167.597 2188.789 2756.88
4 1547.838 1609.13 2530.782 1509.116 0 1071.186 信息 3437.752 624.6915 1348.369
5 541.9545 603.5713 1270.946 2354.782 1026.145 0 204.1122 4501.91 436.0267 401.6861
6 459.8273 581.1262 1058.695 2634.319 1264.167 信息 0 信息 717.3868 300.6823
7 4815.335 5330.784 5322.427 2153.888 3612.119 4600.471 5372.185 0 3998.066 5173.963
8 789.3162 901.9897 1795.072 2139.049 635.1849 434.8522 738.8418 4598.177 0 775.1959
9 794.9219 244.2613 信息 2964.827 1463.854 388.5041 297.126 5215.893 845.9431 0

矩阵中城市不相连的地方有“inf”,对角线有0。我想可视化从(比如说)城市 3 到城市 4 以及从城市 4 到城市 3 的路径。

我想在Python中使用networkx可视化这个矩阵。我没有得到预期的正确输出。根据这个问题:(如何在Python中使用networkx绘制有向图?)以及raz给出的答案,我能够通过“有向和箭头”可视化获得以下图表, 使用以下代码可视化非对称距离矩阵

G = nx.DiGraph(directed=True)

num_nodes = 10 #considering only first 10 cities

for i in range(num_nodes):
    for j in range(num_nodes): 
        if (distance_matrix[i][j] != 0) and (distance_matrix[i][j] != np.inf):
            G.add_edge(i, j, weight=distance_matrix[i][j])


pos = nx.random_layout(G, seed=6)
edge_labels = {key: round(value, 3) for key, value in nx.get_edge_attributes(G, "weight").items()} #Doing this just to control the prescision of the distances

options = {
    'node_color': 'lightblue',
    'node_size': 100,
    'width': 1,
    'arrowstyle': '-|>',
    'arrowsize': 12,
}

plt.figure(figsize=(10, 10))
nx.draw_networkx(G, pos, arrows=True, **options)
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=5)
plt.title("Distance Matrix Visualized as Graph")
plt.show()

我得到了这个可视化非对称距离矩阵的可视化

此处仅显示一侧边缘。我希望显示两侧边缘(显然具有不同的值)。

例如:从城市 3 到城市 4 的边距离为 1386.0443,从城市 4 到城市 3 的边距离为 1509.1162。但该图只绘制了 1509.1162

以下代码

print(G[4][3]['weight'])
print(G[3][4]['weight'])

产量:

1509.11627820888
1386.044382692059

即,该图具有有关两个方向的边缘的信息,但它仍然只显示一侧的边缘。

我需要帮助来正确绘制有向非对称图中任意两个城市之间的两条边(即,一条边从一个城市开始,另一条边以该城市结束)。

python graph visualization networkx distance-matrix
1个回答
0
投票

您可以在

'connectionstyle': 'arc3,rad=-0.1'
draw_networkx
中为边缘添加一些曲率(例如使用选项
draw_networkx_edge_labels
):

options = {
    'node_color': 'lightblue',
    'node_size': 100,
    'width': 1,
    'arrowstyle': '-|>',
    'arrowsize': 12,
    'connectionstyle': 'arc3,rad=-0.1',
}

nx.draw_networkx(G, pos, arrows=True, **options)
nx.draw_networkx_edge_labels(G, pos, connectionstyle=options['connectionstyle'],
                             edge_labels=edge_labels, font_size=5)

输出:

networkx digraph edge labels

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.