Search code examples
rggplot2ggraph

how to use circle pack layout in ggraph library in r


what data format is necessary to create ggraph circlepack layout? It seems to require a hierarchy.

I tried normally vertices and nodes, which apparently doesn't work.

library(ggraph)
library(igraph)
edges=data.frame(from=c('a','b','c'), to= c('c','a','d'))
vertices=data.frame(nodes=c('a','b','c','d'), weight=c(1,2,3,4))
graph <- graph_from_data_frame(edges, vertices = vertices)
ggraph(graph, 'circlepack', weight = 'size') + 
geom_node_circle(size = 0.25, n = 50) + 
coord_fixed()

I then tried a dendrogram object which doesn't work either. If i want to show several groups with sub-items in packed circle, how shall i build the graph object?

the data frame is more like this

df <- data.frame(group=c("a","a","b","b","b"),    subitem=c("x","y","z,"u","v"), size=c(6,2,3,2,5))

Solution

  • A circlepack layout models a hierarchical/tree-like structure with one root and no cycles. To model your df as a circlepack layout, you have to consider that a and b in the group column are both roots. If we add a root to the df, and have both a and b be children of that root, we can visualize it as a circlepack:


    library(ggraph)
    library(igraph)
    library(dplyr)
    
    
    df <- data.frame(group=c("root", "root", "a","a","b","b","b"),    
                     subitem=c("a", "b", "x","y","z","u","v"), 
                     size=c(0, 0, 6,2,3,2,5))
    
    # create a dataframe with the vertices' attributes
    
    vertices <- df %>% 
      distinct(subitem, size) %>% 
      add_row(subitem = "root", size = 0)
    
    graph <- graph_from_data_frame(df, vertices = vertices)
    
    ggraph(graph, layout = "circlepack", weight = 'size') + 
      geom_node_circle(aes(fill =depth)) +
    # adding geom_text to see which circle is which node 
      geom_text(aes(x = x, y = y, label = paste(name, "size=", size))) +
      coord_fixed()