在 R 中使用 graph 和 tidygraph 着色节点?

Colouring nodes using graph and tidygraph in R?

我最近问 关于如何通过变量给节点着色的问题。而且代码效果很好。但是,我回来尝试分别为终端节点着色。例如,如果我创建一些数据,然后将它们转换为 tidygraph 对象并使用 ggraph 绘制它们,那么我会得到如下内容:

library(tidygraph)
library(ggraph)
library(gridExtra)

pal = colorspace::sequential_hcl(palette = "Purples 3", n = 100)


# create some data for the tbl_graph
nodes <- data.frame(name = c("x4", NA, NA),
                    label = c("x4", 5, 2), 
                    value = c(10, 5, 2))

nodes1 <- data.frame(name = c("x4", "x2", NA, NA, "x1", NA, NA),
                     label = c("x4", "x2", 2,   1, "x1", 13, 7),
                     value = c(10, 8, 2, 1, 10, 13, 7))



edges <- data.frame(from = c(1,1), to = c(2,3))
edges1 <- data.frame(from = c(1, 2, 2, 1, 5, 5),
                     to    = c(2, 3, 4, 5, 6, 7))

# create the tbl_graphs
tg <- tbl_graph(nodes = nodes, edges = edges)
tg_1 <- tbl_graph(nodes = nodes1, edges = edges1)


# put into list
myList <- list(tg, tg_1)

# set colours for variables
nodenames <- unique(na.omit(unlist(lapply(myList, .%>%activate(nodes) %>% pull(name) ))))
nodecolors <- setNames(scales::hue_pal(c(0,360)+15, 100, 64, 0, 1)(length(nodenames)), nodenames)
nodecolors 

# plot function
plotFun <- function(List, colors=NULL){
  
  plot <- ggraph(List, "partition") +
    geom_node_tile(aes(fill = name), size = 0.25) +
    geom_node_label(aes(label = label, color = name)) +
    scale_y_reverse() +
    theme_void() +
    theme(legend.position = "none")
  if (!is.null(colors)) {
    plot <- plot + scale_fill_manual(values=colors) + 
      scale_fill_manual(values=colors, na.value= 'grey40')
  }
  plot
}

# create grid of plots
allPlots <- lapply(myList, plotFun, colors=nodecolors)
n <- length(allPlots)
nRow <- floor(sqrt(n))
do.call("grid.arrange", c(allPlots, nrow = nRow))

如您所见,命名节点的颜色都正确,但终端节点的颜色为灰色。我正在尝试通过数据 value 列中的相应值为终端节点着色。我试过更改 scale_fill_manual 函数,但我似乎无法让它工作..

关于如何执行此操作有什么建议吗?

如果我没理解错的话,你想应用不同的颜色映射到 终端节点,将 value 映射到颜色而不是 name,并使用 完全不同的色标。 ggplot2 不直接支持, 但你可以使用例如ggnewscale 对其余应用不同的比例 的情节。

我稍微简化了您的示例以专注于新的秤应用程序:

library(tidygraph)
library(ggraph)

nodes <- data.frame(
  name = c("x4", "x2", NA, NA, "x1", NA, NA),
  label = c("x4", "x2", 2, 1, "x1", 13, 7),
  value = c(10, 8, 2, 1, 10, 13, 7)
)

edges <- data.frame(
  from = c(1, 2, 2, 1, 5, 5),
  to = c(2, 3, 4, 5, 6, 7)
)

tg <- tbl_graph(nodes = nodes, edges = edges)

ggraph(tg, "partition") +
  geom_node_tile(aes(fill = name)) +
  geom_node_label(aes(label = label, color = name)) +
  # Apply different colour/fill scales to terminal nodes
  ggnewscale::new_scale_fill() +
  ggnewscale::new_scale_color() +
  geom_node_tile(
    data = . %>% filter(is.na(name)),
    aes(fill = value)
  ) +
  geom_node_label(
    data = . %>% filter(is.na(name)),
    aes(label = label, color = value)
  )