如何更改 python igraph 中的边方向?
How can I change the direction of edges in python igraph?
我有一个带有单个根顶点的有向树图,其中的方向似乎是任意的。
我希望所有边都从单个根指向各个分支的末端。
我的第一个原始尝试是像下面这样交换源顶点和目标顶点(但正如假设的那样,它不会起作用。
temp = g.es[e_idx].source
g.es[e_idx].source = g.es[e_idx].target
g.es[e_idx].target = temp
是否有一个函数或一组函数允许交换可用的特定边的方向?
或者一种无需更改任何顶点属性即可操纵边的源/目标属性的方法?
如果我需要进一步说明,请告诉我。
非常感谢您的帮助。
这是一个保留所有图形属性的可能解决方案:
- 我们将对顶点重新排序,以便靠近根的顶点排在第一位
- 然后我们使用
to_directed
和 "acyclic"
模式,它将边从较低的索引顶点指向较高的索引顶点
- 最后我们恢复原来的顶点顺序
import igraph as ig
from igraph import Graph
# Set seed for reproducibility
import random
random.seed(123)
# Create an undirected tree. If your tree is not undirected,
# convert it to undirected first.
g = Graph.Tree_Game(10)
# Our chosen root:
root = 3
ig.plot(g, vertex_label=range(g.vcount()), layout = g.layout_reingold_tilford(root=root), bbox=(300,300))
# Distances from the root, will be used for ordering:
dist=g.shortest_paths(source=root)[0]
# This function computes the permutation that would
# sort 'elems'. It also serves as a way to invert
# permutations.
def ordering(elems):
return sorted(range(len(elems)), key=elems.__getitem__)
# Compute orderings based on the distance from the root:
perm = ordering(dist)
invperm = ordering(perm)
# Reorder, direct, restore order:
dg = g.permute_vertices(invperm)
dg.to_directed('acyclic')
dg = dg.permute_vertices(perm)
# Plot again.
# Now the root does not need to be given,
# as it is auto-detected from the directions.
ig.plot(dg, vertex_label=range(g.vcount()), layout='reingold_tilford', bbox=(300,300))
我有一个带有单个根顶点的有向树图,其中的方向似乎是任意的。 我希望所有边都从单个根指向各个分支的末端。
我的第一个原始尝试是像下面这样交换源顶点和目标顶点(但正如假设的那样,它不会起作用。
temp = g.es[e_idx].source
g.es[e_idx].source = g.es[e_idx].target
g.es[e_idx].target = temp
是否有一个函数或一组函数允许交换可用的特定边的方向?
或者一种无需更改任何顶点属性即可操纵边的源/目标属性的方法?
如果我需要进一步说明,请告诉我。
非常感谢您的帮助。
这是一个保留所有图形属性的可能解决方案:
- 我们将对顶点重新排序,以便靠近根的顶点排在第一位
- 然后我们使用
to_directed
和"acyclic"
模式,它将边从较低的索引顶点指向较高的索引顶点 - 最后我们恢复原来的顶点顺序
import igraph as ig
from igraph import Graph
# Set seed for reproducibility
import random
random.seed(123)
# Create an undirected tree. If your tree is not undirected,
# convert it to undirected first.
g = Graph.Tree_Game(10)
# Our chosen root:
root = 3
ig.plot(g, vertex_label=range(g.vcount()), layout = g.layout_reingold_tilford(root=root), bbox=(300,300))
# Distances from the root, will be used for ordering:
dist=g.shortest_paths(source=root)[0]
# This function computes the permutation that would
# sort 'elems'. It also serves as a way to invert
# permutations.
def ordering(elems):
return sorted(range(len(elems)), key=elems.__getitem__)
# Compute orderings based on the distance from the root:
perm = ordering(dist)
invperm = ordering(perm)
# Reorder, direct, restore order:
dg = g.permute_vertices(invperm)
dg.to_directed('acyclic')
dg = dg.permute_vertices(perm)
# Plot again.
# Now the root does not need to be given,
# as it is auto-detected from the directions.
ig.plot(dg, vertex_label=range(g.vcount()), layout='reingold_tilford', bbox=(300,300))