如何在R中使用igraph选择一个图中的节点?

3
在Python中,您可以简单地使用graph.select()(至少在阅读文档时:https://igraph.org/python/doc/api/igraph.VertexSeq.html)来基于值选择一个顶点。我有一个连接共享演员的电影的巨大图形。然而,我只想从该图形中选择一个顶点,然后与其直接邻居绘制它。当我想要仅选择单个顶点时,遇到了问题。
我希望像这样做:
graph.movies.select('Snatch (2000)')

但是没有好运气。 我采取的另一种方法是通过过滤所有其他的 snatch 顶点来抓取单个 snatch 顶点,然后添加边缘。
snatch.graph <- induced.subgraph(g.movies, vids=V(g.movies)$name == 'Snatch (2000)')
snatch.edges <- edges(g.movies, "Snatch (2000)")
add_edges(snatch.graph, snatch.edges$edges)

然而,这会返回一个只有Snatch节点的空图。
我的目标是抓取Snatch节点并绘制该节点、其直接邻居以及它们之间的边缘。有什么建议吗?非常感谢:D 这个问题困扰了我相当长时间-.-
2个回答

3
你可以使用?ego来获取邻居,或者使用?make_ego_graph来形成图形。(根据你的图形是否有向,你可能需要使用mode参数)。
一个例子:
library(igraph)

# create some data
set.seed(71085002)
n = 10
g = random.graph.game(n, 0.25)
V(g)$name = seq_len(n)

# grab neighbours of node "1"
# set mindist = 0 to include node itself
# set order for the stepsize of the neigbourhood; 
nb_g = make_ego_graph(g, order=1, node="1", mindist=0)[[1]]

# plot
# you could use the `layout` argument to 
# keep nodes in the same position
op = par(mfrow=c(1,2), oma=rep(0,4))
  plot(g, vertex.size=0, vertex.label.cex=3, main="Full graph")
  plot(nb_g, vertex.size=0, vertex.label.cex=3, main="Sub graph")
par(op) # reset

enter image description here

如果您只需要邻居节点的列表:
ego(g, order=1, node="1", mindist=0)
# [[1]]
# + 4/10 vertices, named, from 00cfa70:
# [1] 1 4 6 9

1

我认为使用用户@user20650提出的ego方法是全面而有效的。

如果您想查找建立在直接邻居上的子图,这里有另一个选项,它应用了distances+induced_subgraph

> induced_subgraph(g, which(distances(g, "1") <= 1))
IGRAPH 99f872b UN-- 4 3 -- Erdos renyi (gnp) graph
+ attr: name (g/c), type (g/c), loops (g/l), p (g/n), name (v/n)
+ edges from 99f872b (vertex names):
[1] 1--4 1--6 1--9

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接