2

我有一个标准的 data.Frame,其中包含一些分类列和一个数字列。它代表一个嵌套的实验设计(但这并不重要),如下所示:

set.seed(1234)
data = data.frame(toplevel=c("A","A","A","A", "B", "B", "B"), 
                  second = c("A1", "A1", "A2", "A2", "B1", "B1", "B2"),
                  experiments = paste0("exp_00", 1:7),
                  values = runif(7, 1,100))
####   toplevel second experiments   values
#### 1        A     A1     exp_001 12.25664
#### 2        A     A1     exp_002 62.60764
#### 3        A     A2     exp_003 61.31820
#### 4        A     A2     exp_004 62.71456
#### 5        B     B1     exp_005 86.23062
#### ...

我想用这个代码(左图!)做同样的情节: https ://www.r-graph-gallery.com/314-custom-circle-packing-with-several-levels/

我不知道如何将我的数据框变成“igraph”data.Frame 并继续执行建议绘制的代码(我没有fromto列..)。values给定我的示例数据(圆圈大小代表列),我想要的输出看起来像右边的图。我尝试使用失败graph_from_data_frame

在此处输入图像描述

谢谢编辑:到目前为止我尝试的代码(我只有部分图表..?)

library(tidyverse); library(igraph); library(ggraph)
edges = rbind.data.frame(data[,1:2] %>% setNames(c("from", "to")), data[, 2:3] %>% setNames(c("from", "to")))
vertices = bind_rows(
  data %>% group_by(toplevel) %>% summarize(values=sum(values)) %>% select(name=toplevel, values),
  data %>% group_by(second) %>% summarize(values=sum(values)) %>% select(name=second, values),
  data %>% select(name=experiments, values)
)
mygraph=graph_from_data_frame(edges, directed = TRUE, vertices = vertices)
ggraph(mygraph, layout = 'circlepack',weight="values") + 
  geom_node_circle() +
  theme_void()
4

1 回答 1

1

我认为你目前的尝试绝对是在正确的轨道上。可能有帮助的一个技巧是添加一个额外的“根”节点,您的两个顶级节点都连接到该节点。目前,因为您的顶级节点之间根本没有连接,所以 ggraph 只绘制其中一组:

edges = rbind.data.frame(
    data[,1:2] %>% setNames(c("from", "to")), 
    data[, 2:3] %>% setNames(c("from", "to")),
    data.frame(from = c("root", "root"), to = c("A", "B")))
vertices = bind_rows(
    data.frame(name = "root", values = sum(data$values)),
    data %>% group_by(toplevel) %>% summarize(values=sum(values)) %>% select(name=toplevel, values),
    data %>% group_by(second) %>% summarize(values=sum(values)) %>% select(name=second, values),
    data %>% select(name=experiments, values),
)
mygraph=graph_from_data_frame(edges, directed = TRUE, vertices = vertices)
ggraph(mygraph, layout = 'circlepack',weight="values") + 
    geom_node_circle(aes(fill = depth)) +
    geom_node_label(aes(label = name)) +
    theme_void()
于 2019-03-21T00:02:24.330 回答