Sarab
Sarab

Reputation: 111

How do I add self loops to a ggraph?

I am trying to plot a network analysis of students' province of origin and where they go for school. I am using ggraph. The graph doesn't show self-loops (i.e. students who attend school in the province they are from). How do I add that? Here is my code:

routes_tidy <- tbl_graph(nodes = nodes, edges = edges, directed = FALSE)

ggraph(routes_tidy, layout = "linear") + 
geom_edge_arc(aes(width = weight), alpha = 0.6, fold = TRUE) +
scale_edge_width(range = c(0.2, 10))+
geom_node_text(aes(label = label), repel = FALSE)+
labs(edge_weight = "Letters")+
theme_graph()

Upvotes: 2

Views: 806

Answers (1)

elliot
elliot

Reputation: 1944

You can use geom_edge_loop to show loops in your graph. See the code/output below. I created some new data as none was provided.

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

set.seed(123)
routes_tidy <- erdos.renyi.game(25, .05, loops = T)

V(routes_tidy)$name <- 1:vcount(routes_tidy)

ggraph(routes_tidy, layout = "linear") + 
  geom_edge_arc(alpha = 0.6, fold = TRUE) +
  geom_edge_loop()+ 
  geom_node_text(aes(label = name), repel = FALSE)+
  labs(edge_weight = "Letters")+
  theme_graph()+
  labs(caption  = 'Node 6 shows a self-loop.')

enter image description here

Upvotes: 4

Related Questions