Ryan
Ryan

Reputation: 33

Control order of nodes in ggraph tree

Is it possible to control the horizontal order of nodes in a ggraph tree?

library(ggraph)
library(igraph)
library(tidyverse)

mygraph <- tibble(from = c("A", "A", "C", "C"), to = c( "B", "C", "D", "E")) %>%
  graph_from_data_frame()
V(mygraph)$node_label <- names(V(mygraph))
mygraph %>%
  ggraph(layout = 'tree', circular = FALSE) + 
  geom_edge_diagonal(edge_width = 0.12) +
  geom_node_label(aes(label=node_label), size = 10,
                  label.size = 0, label.padding = unit(0.1, "lines")) +
  theme_void() +
  coord_fixed()

enter image description here

I want to be able to keep node B as the left branch and node C and its subsequent nodes as the right branch.

Upvotes: 3

Views: 743

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76412

The graphs nodes are not in the wanted order, reorder them first. This comment has a simple way I will use below.

suppressPackageStartupMessages(library(tidyverse))
suppressPackageStartupMessages(library(ggraph))
suppressPackageStartupMessages(library(igraph))

mygraph <- tibble(from = c("A", "A", "C", "C"), to = c( "B", "C", "D", "E")) %>%
  graph_from_data_frame()

# out of order
names(V(mygraph))
#> [1] "A" "C" "B" "D" "E"

# order the nodes
s <- sort(names(V(mygraph)))
mygraph <- permute(mygraph, match(V(mygraph)$name, s))

Created on 2022-03-12 by the reprex package (v2.0.1)

Now assign the node labels and plot the graph.

V(mygraph)$node_label <- names(V(mygraph))

mygraph %>%
  ggraph(layout = 'tree', circular = FALSE) + 
  geom_edge_diagonal(edge_width = 0.12) +
  geom_node_label(aes(label=node_label), size = 10,
                  label.size = 0, label.padding = unit(0.1, "lines")) +
  theme_void() +
  coord_fixed()

Created on 2022-03-12 by the reprex package (v2.0.1)

Upvotes: 3

Related Questions