Controlling facet order in ggraph

Viewed 666

I want to plot a graph using facets, where the edges vary between panels. The panels are automatically ordered alphabetically (as is customary in ggplot). A simple example:

library(igraph)
library(ggraph)

g <- make_empty_graph() + 
  vertices(1:2) +
  edges(1:2, 2:1, g = c('b', 'a'))

ggraph(g, 'kk') + 
  geom_edge_link(arrow = grid::arrow()) + 
  geom_node_label(aes(label = name)) +
  facet_edges(~g)

enter image description here

This is great, the node positions are presevered, but the edges differ depending on g.

However, I want to choose the order that facets appear. So in this case, first b then a, just like I ordered them while creating the graph above.

In ggplot one would change the order of the factor g. However, creating a layout does not show g:

create_layout(g, 'kk')
           x             y name ggraph.orig_index circular ggraph.index
1 -0.9021575 -1.410825e+00    1                 1    FALSE            1
2 -1.0000000  1.224606e-16    2                 2    FALSE            2

Changing the edge attributes into a factor manually, does change the ordering, but the labels are coerced to numeric:

g2 <- make_empty_graph() + 
  vertices(1:2) +
  edges(1:2, 2:1, g = factor(c('b', 'a'), levels = c('b', 'a')))

ggraph(g2, 'kk') + 
  geom_edge_link(arrow = grid::arrow()) + 
  geom_node_label(aes(label = name)) +
  facet_edges(~g)

enter image description here

How can I give custom ordering for the facets?

2 Answers
Related