As the title says. I have a graph object created using igraph::sample_grg()
, which I want to plot using ggraph
, with nodes positioned according to the node attributes x
and y
. What I have tried:
Create graph:
set.seed(1234)
library(igraph)
library(ggraph)
library(tidygraph)
g <- sample_grg(5, 0.4, torus = FALSE, coords = TRUE)
The graph comes with x
and y
attributes which should be the node positions
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
Attempt 1
ggraph(g) +
geom_edge_link() +
geom_node_point()
Error in graph_to_tree(graph, mode = direction) : Graph must be directed
I don't have or want a directed graph.
Attempt 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.
Attempt 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
Attempt 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
Attempt 5 following this question:
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)))
I feel like I am missing something really obvious, any advice would be much appreciated.
Since you have enabled coords = TRUE
when generating g
, the layout coordinates names have been given as x
and y
.
To avoid collision, you should name layout l1
with different column names, e.g., lx
or ly
,
l1 <- data.frame(lx = NA, ly = NA)
ggraph(g, l1) +
geom_edge_link() +
geom_node_point()
If you disable coords =
, i.e.,
g <- sample_grg(5, 0.4, torus = FALSE, coords = FALSE)
then you can provide your own coordinates with column names x
and y
(since no such columns will be produce if you don't specify their values), e.g.,
l1 <- data.frame(x = 1:5, y = 5:1)
ggraph(g, l1) +
geom_edge_link() +
geom_node_point()
and you will see