zesla
zesla

Reputation: 11833

How to adjust the width of edges by weight in ggraph network in r

I need to generate a network with ggraph in r. What I want is adjust the edge width by weight variable (or the size of nodes). Does anyone know how I can do that? Thanks a lot.

Example code below:

library(ggraph)
library(igraph)
data=data.frame(w1=rep('like', 5), 
           w2 = c('apple', 'orange', 'pear','peach', 'banana'),
           weight= c(2,3,5,8, 15))
data %>% 
  graph_from_data_frame() %>% 
  ggraph(layout = "fr") +
  geom_edge_link(alpha = .25) +
  geom_node_point(color = "blue", size = 2) + 
  geom_node_text(aes(label = name),  repel = TRUE)

Upvotes: 4

Views: 7796

Answers (1)

elliot
elliot

Reputation: 1954

Yes, you can do this with the width aes in most geom_edge_*'s. Also, you can use scale_edge_width to finetune the min/max width according to the weighted variable. See the two examples below.

Also, I believe there was an issue with this aesthetic to do with ggforce (it was causing me trouble too). Make sure you've updated to the most recent versions of ggraph and ggforce.

library(ggraph)
library(igraph)
data=data.frame(w1=rep('like', 5), 
                w2 = c('apple', 'orange', 'pear','peach', 'banana'),
                weight= c(2,3,5,8, 15))

The first with default weigthts

data %>% 
  graph_from_data_frame() %>% 
  ggraph(layout = "fr") +
  geom_edge_link(alpha = .25, 
                 aes(width = weight)) +
  geom_node_point(color = "blue", size = 2) + 
  geom_node_text(aes(label = name),  repel = TRUE)+
  theme_graph()+
  labs(title = 'Graph with weighted edges', 
       subtitle = 'No scaling')

enter image description here

Using scale_edges_width to set the range. NOTE - scale_edges* can take multiple arguments.

data %>% 
  graph_from_data_frame() %>% 
  ggraph(layout = "fr") +
  geom_edge_link(alpha = .25, 
                 aes(width = weight)) +
  geom_node_point(color = "blue", size = 2) + 
  geom_node_text(aes(label = name),  repel = TRUE)+
  scale_edge_width(range = c(1, 20))+ # control size
  theme_graph()+
  labs(title = 'Graph with weighted edges', 
       subtitle = 'Scaling add with scale_edge_width()')

enter image description here

Upvotes: 6

Related Questions