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