r - 在一行中堆叠 n 个来自循环的图
r - stack n number of plots coming from a loop in one row
我正在尝试堆叠多个组合在列表中并来自 purrr::map
的地块。
条件是:
- 不使用
facet_wrap
或 facet_grid
- 我知道这可以用这些功能来完成,但我有另一个限制因素不允许使用它们
- 列表中的地块数量可能会有所不同 - 因此它不是一个常数
重现问题的可重现示例:
library(dplyr)
library(tidyr)
library(purrr)
# a sample dataframe
df <- data.frame(gr = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 3),
a = rnorm(10, 5, 3),
b = rnorm(10, 5, 3)) %>%
group_by(gr) %>%
nest()
# a plotting function
plotting <- function(x) {
ggplot(x) + geom_point(aes(a,b))
}
# getting the list of the plots
lst <- map(df$data,plotting)
我可以使用patchwork
包手动解决问题:
library(patchwork)
lst[[1]] + lst[[2]] + lst[[3]] + patchwork::plot_layout(nrow = 1)
或gridExtra
包:
library(gridExtra)
grid.arrange(lst[[1]], lst[[2]], lst[[3]],nrow = 1)
但如果地块数量不同,这将不起作用。感谢您提供有关如何自动执行此操作的任何想法。
cowplot 中的 plot_grid
函数接受绘图列表作为输入。
cowplot::plot_grid(plotlist=lst, nrow=1)
我正在尝试堆叠多个组合在列表中并来自 purrr::map
的地块。
条件是:
- 不使用
facet_wrap
或facet_grid
- 我知道这可以用这些功能来完成,但我有另一个限制因素不允许使用它们 - 列表中的地块数量可能会有所不同 - 因此它不是一个常数
重现问题的可重现示例:
library(dplyr)
library(tidyr)
library(purrr)
# a sample dataframe
df <- data.frame(gr = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 3),
a = rnorm(10, 5, 3),
b = rnorm(10, 5, 3)) %>%
group_by(gr) %>%
nest()
# a plotting function
plotting <- function(x) {
ggplot(x) + geom_point(aes(a,b))
}
# getting the list of the plots
lst <- map(df$data,plotting)
我可以使用patchwork
包手动解决问题:
library(patchwork)
lst[[1]] + lst[[2]] + lst[[3]] + patchwork::plot_layout(nrow = 1)
或gridExtra
包:
library(gridExtra)
grid.arrange(lst[[1]], lst[[2]], lst[[3]],nrow = 1)
但如果地块数量不同,这将不起作用。感谢您提供有关如何自动执行此操作的任何想法。
cowplot 中的 plot_grid
函数接受绘图列表作为输入。
cowplot::plot_grid(plotlist=lst, nrow=1)