如何解决使用提供的节点坐标绘制 ggraph
正如标题所说。我有一个使用 igraph::sample_grg()
创建的图形对象,我想使用 ggraph
绘制它,节点根据节点属性 x
和 y
定位。我尝试过的:
创建图表:
set.seed(1234)
library(igraph)
library(ggraph)
library(tidygraph)
g <- sample_grg(5,0.4,torus = FALSE,coords = TRUE)
该图带有 x
和 y
属性,它们应该是节点位置
vertex.attributes(g)
$x
[1] 0.009495756 0.113703411 0.609274733 0.666083758 0.860915384
$y
[1] 0.6222994 0.6233794 0.6403106 0.2325505 0.5142511
尝试 1
ggraph(g) +
geom_edge_link() +
geom_node_point()
Error in graph_to_tree(graph,mode = direction) : Graph must be directed
我没有或不想要有向图。
尝试 2
l1 = data.frame(x = V(g)$x,y = V(g)$y)
ggraph(g,layout = l1) +
geom_edge_link() +
geom_node_point()
Error: `data` must be uniquely named but has duplicate columns
Run `rlang::last_error()` to see where the error occurred.
尝试 3
l2 <- create_layout(g,layout = l1)
l2 <- l2[,-c(1:2)]
ggraph(l2,layout = l2) +
geom_edge_link() +
geom_node_point()
Error in .register_graph_context(attr(plot$data,"graph"),free = TRUE) :
is.tbl_graph(graph) is not TRUE
尝试 4
g2 <- as_tbl_graph(g)
ggraph(g2,layout = "manual") +
geom_edge_link() +
geom_node_point()
Error in eval_tidy(x,.N()) : object '' not found
在 this question 之后尝试 5 次:
ggraph(g,layout = "manual",circular = FALSE,node.positions = l1) +
geom_edge_link() +
geom_node_point()
Error in layout_fun(graph,circular = circular,...) :
unused argument (node.positions = list(c(0.0612166156060994,0.0649281670339406,0.250601968728006,0.726055516628549,0.916498943232),c(0.979841426480561,0.450912220636383,0.283102283952758,0.782102265860885,0.663251199992374)))
我觉得我遗漏了一些非常明显的东西,任何建议将不胜感激。
解决方法
由于您在生成 coords = TRUE
时启用了 g
,因此布局坐标名称已指定为 x
和 y
。
为避免冲突,您应该使用不同的列名命名布局 l1
,例如,lx
或 ly
,
l1 <- data.frame(lx = NA,ly = NA)
ggraph(g,l1) +
geom_edge_link() +
geom_node_point()
如果您禁用 coords =
,即,
g <- sample_grg(5,0.4,torus = FALSE,coords = FALSE)
然后您可以使用列名 x
和 y
提供您自己的坐标(因为如果您不指定它们的值,将不会产生这样的列),例如,
l1 <- data.frame(x = 1:5,y = 5:1)
ggraph(g,l1) +
geom_edge_link() +
geom_node_point()
你会看到
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。