2

我最近问了这个关于如何按变量为节点着色的问题。而且代码效果很好。但是,我回来尝试分别为终端节点着色。例如,如果我创建一些数据,然后将它们转换为 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功能,但我似乎无法让它工作..

关于我如何做到这一点的任何建议?

4

1 回答 1

2

如果我理解正确,您想对终端节点应用不同的颜色映射,映射value到 color 而不是name,并完全使用不同的色标。ggplot2不直接支持,但您可以使用 eg 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)
  )

于 2022-02-21T15:11:42.660 回答