Ggplot grid.arrange 全部排成一行,看起来像一个无缝图

Gggplot grid.arrange all in one row to look like a seamless plot

我正在尝试实施来自 here 的解决方案。不幸的是,我无法通过使用 gridextra 包的解决方案来上传嵌套的 facets 包并尝试格式化 facet 标题。

但是,我似乎无法弄清楚如何将所有图表放在一行中,因为它看起来像一个条形图。需要以某种方式修改此行:grid.arrange(., ncol = 1)。在我的数据中,所有图的大小都相同,每个图有两个数据点。

借用的代码是:

library(ggplot2)
library(gridExtra)
library(dplyr)

dat <-
  structure(list(Species = c("Acanthocyclops robustus", "Acroperus harpae", 
  "Alona affinis", "Ascaphus truei", "Bosmina longirostris"), Intercept = c(-36.1182388331068, 
  -27.2140776216155, -25.7920464721491, -39.2233884219763, -31.4301301084581
  ), B = c(0.919397836908493, 0.716601987210452, 0.685455190113372, 
  1.04159758611351, 0.81077051300147), Bconf = c(0.407917065756464, 
  0.181611850119198, 0.254101713856315, 0.708582768458448, 0.234313394549538
  ), Order = c("Cyclopoida", "Diplostraca", "Diplostraca", "Anura", 
  "Diplostraca"), Family = c("Cyclopidae", "Chydoridae", "Chydoridae", 
  "Leiopelmatidae", "Bosminidae")), .Names = c("Species", "Intercept", 
  "B", "Bconf", "Order", "Family"), row.names = c(NA, 5L), class = "data.frame")

dat

# A ggplot object with NO data.  Omit the order from the facet_grid call
g <- 
  ggplot() +
  aes(Species, B) +
  geom_point() +
  facet_grid(. ~ Family,
             scales = "free", space = "free") +
  ylim(range(dat$B)) +
  xlab("")

# Build a seperate graphic for each Order and title
plots <-
  lapply(unique(dat$Order), function(o) {
           g %+% dplyr::filter_(dat, ~ Order == o) + ggtitle(o)
             })

# build as Grobs and plot via gridExtra::grid.arrange
plots %>%
  lapply(ggplotGrob) %>%
  arrangeGrob(grobs = .) %>%
  grid.arrange(., ncol = 1)

我建议采用 patchwork 打包方法。您可以以实用的方式定义所需的行数和列数。接下来是我们的数据为 dat:

的代码

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

library(ggplot2)
library(dplyr)
library(patchwork)
#Create list
List <- split(dat,dat$Order)

我们为绘图构建函数:

#Now function to plot
myplotfun <- function(x)
{
  G <- ggplot(x,aes(x=Family,y=B))+
    geom_point() +
    facet_grid(. ~ Family,
               scales = "free", space = "free") +
    ylim(range(x$B)) +
    xlab("")+ggtitle(unique(x$Order))
  return(G)
}

最后我们应用函数并使用 patchwork 函数绘图:

#Apply for plots
List2 <- lapply(List,myplotfun)
#Wrap final plot
wrap_plots(List2,nrow = 1)

输出:

您可以根据需要添加其他详细信息。