how to use circle pack layout in ggraph library in r

社会主义新天地 提交于 2019-12-11 06:26:48

问题


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))

回答1:


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()



来源:https://stackoverflow.com/questions/43739749/how-to-use-circle-pack-layout-in-ggraph-library-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!