Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selectively color/size nodes in ggraph

I'm using tidygraph and ggraph to plot a network. Is there a way to selectively manipulate nodes? Specifically, size and color, separately.

# example data
    rstat_nodes <- data.frame(name = c("Hadley", "David", "Romain", "Julia"))
    rstat_edges <- data.frame(from = c(1, 1, 1, 2, 3, 3, 4, 4, 4), 
                              to = c(2, 3, 4, 1, 1, 2, 1, 2, 3))
    gr <- tbl_graph(nodes = rstat_nodes, edges = rstat_edges)

    as_tbl_graph(gr) %>% 
      mutate(centrality = centrality_degree(normalized = T)) %>% 
      ggraph(layout = 'auto') + 
      #geom_edge_link() +
      geom_edge_arc(curvature=0.2,alpha=0.5) + 
      geom_node_point(aes(size = 0.2, colour = centrality)) + 
      scale_color_viridis(guide = 'legend') + 
      ggtitle("Network Degree Centrality (Normalized)") +
      theme_graph()
like image 383
riverotter Avatar asked Nov 25 '25 19:11

riverotter


1 Answers

Yes, you can use activate from the tidygraph package to access the nodes and edges dataframes. You can then use dplyr to manipulate the data in each file. You can also pipe directly into a ggraph.

library(tidyverse)
library(igraph)
library(ggraph)
library(tidygraph)
library(graphlayouts)
library(scales)


# example data
rstat_nodes <-
  data.frame(name = c("Hadley", "David", "Romain", "Julia"))
rstat_edges <- data.frame(from = c(1, 1, 1, 2, 3, 3, 4, 4, 4),
                          to = c(2, 3, 4, 1, 1, 2, 1, 2, 3))

gr <- tbl_graph(nodes = rstat_nodes, edges = rstat_edges)

gr %>% 
  activate(nodes) %>% # use dplyr on nodes
  mutate(David = 
           case_when(name == 'David' ~ 2, T ~ 0), 
         David = as.character(David)) %>% 
  activate(edges) %>% # same on edge list
  mutate(David = case_when(from == 2 ~ 1, T ~ 0), 
         David = as.character(David)) %>% 
  ggraph(., layout = 'auto')+
  geom_edge_link(aes(color = David), 
                 width = 1)+
  geom_node_point(aes(color = David), 
                  size = 5)+
  geom_node_text(aes(label = name), 
                 nudge_x = .05, 
                 nudge_y = .05)

enter image description here

like image 131
elliot Avatar answered Nov 27 '25 09:11

elliot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!