簡體   English   中英

在R中使用整潔圖時按變量着色?

[英]Colouring by variable when using tidy graph in R?

我試圖想出一種方法來一致地為多個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)

然后我有一個繪圖功能,允許我一次顯示所有繪圖。 我使用grid.arrange包中的gridExtra執行此操作,如下所示:

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為紅色,第二個圖中的x4為藍色。

我試圖找到一種方法,使變量label的顏色在所有圖中保持一致。 也許使用grid.arrange不是最好的解決方案!?

任何幫助表示贊賞。

由於每個圖對其他圖一無所知,因此最好自己分配顏色。 首先,您可以提取所有節點名稱並為其分配顏色

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))

具有協調節點名稱顏色的繪圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM