mrjoh3 / cytoscape

An R HTMLWidget wrapper for Cytoscape.js
GNU General Public License v3.0
6 stars 2 forks source link

Cytoscape.js with "Groups" #8

Closed gilhornung closed 5 years ago

gilhornung commented 5 years ago

Hi,

I want to know if there is support for having networks with groups. An example can be found in cola.js https://cytoscape.org/cytoscape.js-cola/demo-compound.html

Thank you,

Gil

gilhornung commented 5 years ago

I was able to add groups, but how do I modify their colors independent of the nodes?

df <- cytoscape::comtrade

nodes <- data_frame(id = unique(c(df$reporter, df$partner)), stringsAsFactors = FALSE) %>% 
  mutate(parent = ifelse(stringr::str_detect(id, "^I"),"Italy","Brazil"))

edges <- df %>%
    dplyr::select(source = reporter,
                  target = partner) %>%
    dplyr::mutate(id = paste(source, '_', target))

cytoscape(nodes = nodes, edges = edges) %>% 
  node_style('background-color' = '#B0C4DE') %>% 
  cola_layout(avoidOverlap = T)
gilhornung commented 5 years ago

After quite a bit of googling I was able to find a solution to color different nodes in different colors:

df <- cytoscape::comtrade

nodes <- data_frame(id = unique(c(df$reporter, df$partner)), stringsAsFactors = FALSE) %>% 
  # Define groups
  mutate(parent = ifelse(id %in% c("Nigeria", "Kenya", "South Africa"),"Africa","Not Africa")) %>% 
  # Define colors
  mutate(node_color = ifelse(parent=="Africa","forestgreen","darkorange")) %>%
  # Add the nodes of the two groups, Africa and "Not Africa"
  bind_rows(data.frame(id = c("Africa", "Not Africa"), node_color="whitesmoke"))

edges <- df %>%
    dplyr::select(source = reporter,
                  target = partner) %>%
    dplyr::mutate(id = paste0(source, '-', target))

cytoscape(nodes = nodes, edges = edges) %>% 
  node_style('background-color' = 'data(node_color)') %>% 
  cola_layout(avoidOverlap = T)
mrjoh3 commented 5 years ago

Hi @gilhornung thanks for figuring this out. Do you mind if I add your example to the readme so others can see how its done?

gilhornung commented 5 years ago

Sure! And thank you for the creating this HTMLWidget!

gilhornung commented 5 years ago

btw, are you sure that you put the stringsAsFactors = FALSE in the right place?

mrjoh3 commented 5 years ago

Yes stringasfactors is correct in the original example. But in your example it is not needed. It is the difference between data.frame and data_frame.