gpt4 book ai didi

python - nx.draw() 将边绘制为双向,即使它们是单向的

转载 作者:行者123 更新时间:2023-12-04 15:03:35 24 4
gpt4 key购买 nike

因此考虑一个每条边都是双向的格子。现在我有一些代码可以删除一些边,以减少双向边的百分比并增加单向边的百分比:

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
from random import shuffle

G = nx.grid_2d_graph(20,20, periodic=True)
G = nx.relabel.convert_node_labels_to_integers(G)
G2 = nx.DiGraph(G)
nx.set_edge_attributes(G2, values = 1, name = 'weight')
edge_list = list(G2.edges())
shuffle(edge_list)

remove_list = []
seen = []

for (u,v) in edge_list:
seen.append((u,v))
if (v,u) in edge_list:
if (v,u) not in seen:
sample = rd.sample([(u,v), (v,u)],1)[0]
if len(remove_list)< 0.8*(len(edge_list)/2):
remove_list.append(sample)
else:
break

G2.remove_edges_from(remove_list)

现在我将单向边保存在列表中:

H = [(u,v) for (u,v) in G2.edges if (v,u) not in G2.edges]

H[:10]

[(0, 20),
(0, 1),
(0, 380),
(1, 2),
(2, 22),
(2, 382),
(3, 4),
(5, 4),
(5, 25),
(5, 6)]

我现在要做的是绘制这个格子:

edge_color = ['red' if (u,v) in H else 'black' for (u,v) in G2.edges] ## uni-directional edges will be red and bi-directional ones will be black

pos = {(x,y):(y,-x) for x,y in product(range(size), range(size))}
pos1 = {i: value for i, value in zip(range(size**2), pos.values())}## assign the nodes to their positions

plt.figure(figsize=(40, 40))
nx.draw(G2,node_size=3000,node_color='lightgreen', with_labels=True, pos=pos1, width=5, edge_color = edge_color)

问题在于,在绘图中我有双向的红色边缘,这是错误的 enter image description here

enter image description here

让我们将 H[:10] 的输出与绘图进行比较:

如您所见,边 (0,1) 绘制正确,但有两个箭头表明它是双向的,即使它不是。另一个例子是边 (1,21),它是双向的,被涂成红色。有人可以帮我解决这个问题吗?

最佳答案

G = nx.grid_2d_graph(20,20, periodic=True)

来自nx.grid_2d_graph docs :

periodic (bool or iterable) – If periodic is True, both dimensions are periodic. If False, none are periodic. If periodic is iterable, it should yield 2 bool values indicating whether the 1st and 2nd axes, respectively, are periodic.

我不知道什么是周期性网格,所以我做了一点研究(谷歌),发现了这个:

来自 Matarazzo, U., Tsur, D., & Ziv-Ukelson, M. (2014). Efficient all path score computations on grid graphs. Theoretical Computer Science, 525, 138-149. :

A periodic grid graph is an infinite graph obtained by concatenating horizontally an infinite number of a (finite) grid graph.

结论

这对我来说仍然很神秘,但你可以在你获得的结果中看到,边缘似乎以某种方式重叠(就像绘制了不止一张图......)。
因此,由于这种“周期性”特征,您似乎获得了一些意想不到的结果。删除 periodic=True 并将此值恢复为默认值 False 可解决问题:

G = nx.grid_2d_graph(20,20)

result

关于python - nx.draw() 将边绘制为双向,即使它们是单向的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66556177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com