data.frame 嵌套因子进入 igraph 气泡图

data.frame with nested factors into igraph bubble graph

我有一个标准 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 并继续使用建议绘制的代码(我没有 from 列..)。根据我的示例数据(圆圈大小代表 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()

我认为你目前的尝试肯定是在正确的轨道上。一个可能有用的技巧是添加一个额外的 "root" 节点,您的两个顶级节点都连接到该节点。目前因为你的顶级节点之间根本没有连接,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()