如何使用 ggplot 在 R 中创建不均匀的 facet_wrap 网格?

How to create uneven facet_wrap grid in R with ggplot?

我目前正在使用 R 中的 ggplot2 绘制图表,我想在其中使用 facet_wrap 创建 5 个子图。

到目前为止,这是我的代码:

# getting the data
data = structure(list(type = c("red", "blue", "orange", "yellow", "green", 
       "red", "blue", "orange", "yellow", "green", "red", "blue", "orange", 
       "yellow", "green", "red", "blue", "orange", "yellow", "green"), 
       cond = c("new", "new", "new", "new", "new", "old", "old", 
       "old", "old", "old", "new", "new", "new", "new", "new", "old", 
       "old", "old", "old", "old"), fact = c("light", "light", "light", 
       "light", "light", "light", "light", "light", "light", "light", 
       "shiny", "shiny", "shiny", "shiny", "shiny", "shiny", "shiny", 
       "shiny", "shiny", "shiny"), score = c(2L, 4L, 8L, 6L, 10L, 3L, 
       5L, 9L, 1L, 3L, 12L, 14L, 18L, 16L, 20L, 13L, 15L, 19L, 11L, 
       13L)), class = "data.frame", row.names = c(NA, -20L))

library(ggplot2)

ggplot(data=data, aes(x=cond, y=score, fill=fact)) +
  geom_bar(stat="identity", position=position_dodge()) +
  theme_bw() + facet_wrap(. ~ type, ncol=3) 

这将创建以下图:

但是,由于其中一种颜色比其他颜色重要得多,我想创建以下选项之一:

有谁知道如何让 facet_wrap 做到这一点,或者可以告诉我另一个创建这个的方法吗?

干杯, 最大值

使用 patchwork 尝试这种方法,您必须将 type 变量格式化为因数以获得所需的顺序,然后使用函数绘制。之后,您可以编写所需的情节。我已经为你设计了这个功能,这属于你问题中的选项 2。这里的代码:

library(ggplot2)
library(patchwork)
#Data format
data$type <- factor(data$type,
                    levels = c("blue","green","orange", "red", "yellow"),
                    ordered = T)

我们为我们的数据创建一个列表:

#Create list
List <- split(data,data$type)

现在,绘图函数:

#Create isolate plots
myplot <- function(x)
{
  text <- unique(as.character(x$type))
  #Plot
  G <- ggplot(data=x, aes(x=cond, y=score, fill=fact)) +
    geom_bar(stat="identity", position=position_dodge()) +
    theme_bw() + ggtitle(text)+
    theme(plot.title = element_text(hjust=0.5))
  return(G)
}

然后,我们开始构建地块:

#Plot for only first plot
P1 <- myplot(List[[1]])
P2 <- wrap_plots(lapply(List[-1], myplot),ncol = 2)

最后,我们整理剧情:

#Now wrap plots
P3 <- P1 + P2
P4 <- P3 +  plot_layout(guides = 'collect')

并且输出:

下面是混合 patchwork 和 facet 的方法。

blue 创建一个图,为其他所有内容创建另一个图。从蓝色图中删除图例并从另一个中删除 y 轴标题。

library(tidyverse)
library(patchwork)

p_other <-
  data %>%
  filter(type != "blue") %>%
  ggplot(aes(x = cond, y = score, fill = fact)) +
    geom_bar(stat = "identity", position = position_dodge()) +
    theme_bw() +
    facet_wrap(. ~ type, ncol = 2) +
    theme(axis.title.y = element_blank())

p_blue <-
  data %>%
  filter(type == "blue") %>%
  ggplot(aes(x = cond, y = score, fill = fact)) +
    geom_bar(stat = "identity", position = position_dodge()) +
    theme_bw() +
    facet_wrap(. ~ type, ncol = 2) +
    theme(legend.position = "none")

使用拼凑的 | 添加一列。

(p_blue | p_other) + plot_layout(widths = c(1, 2))