我正在尝试想出一种方法来一致地对多个tidygraph图进行着色。现在的问题是,当我一次在屏幕上绘制多个图时,tidygraph会为每个变量选择不同的颜色。希望我下面的例子能解释这个问题。
首先,我创建了一些数据,将它们转换为tidygraph对象,并将它们放在一个列表中:
library(tidygraph)
library(ggraph)
library(gridExtra)
# create some data for the tbl_graph
nodes <- data.frame(name = c("x4", NA, NA),
label = c("x4", 5, 2))
nodes1 <- data.frame(name = c("x4", "x2", NA, NA, "x1", NA, NA),
label = c("x4", "x2", 2, 1, "x1", 2, 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)然后我有一个绘图函数,它允许我一次显示所有的绘图。我使用gridExtra包中的grid.arrange完成此操作,如下所示:
plotFun <- function(List){
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")
}
# Display all plots
allPlots <- lapply(myList, plotFun)
n <- length(allPlots)
nRow <- floor(sqrt(n))
do.call("grid.arrange", c(allPlots, nrow = nRow))这将产生如下所示的结果:

正如您所看到的,它通过变量label为每个单独的绘图着色。这会导致相同的变量label在每个图中以不同的颜色显示。例如,第一个打印中的x4是红色的,第二个打印中的是蓝色的。
我正在尝试找到一种方法,使变量的label的颜色在所有绘图中保持一致。也许使用grid.arrange不是最好的解决方案!?
任何帮助都是非常感谢的。
发布于 2021-10-29 18:05:10
由于每个图都不知道其他图的任何信息,因此最好自己指定颜色。首先,您可以提取所有节点名称并为其分配颜色
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
# x4 x2 x1
# "#F5736A" "#00B734" "#5E99FF"我们使用scales::hue_pal来获取“默认”的ggplot颜色,但您可以使用任何您喜欢的颜色。然后,我们只需要使用这些颜色自定义绘图的颜色/填充比例。
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_color_manual(values=colors, na.value="grey")
}
plot
}
allPlots <- lapply(myList, plotFun, colors=nodecolors)
n <- length(allPlots)
nRow <- floor(sqrt(n))
do.call("grid.arrange", c(allPlots, nrow = nRow))

https://stackoverflow.com/questions/69770047
复制相似问题