使用应用函数时如何控制 row/column-wise 绘图打印
How to control the row/column-wise printing of plots when using apply functions
考虑以下数据框:
dat <- data.frame(
ID = c(1:200),
var1 = rnorm(200),
var2 = rnorm(200),
var3 = rnorm(200),
var4 = rnorm(200)
)
我们想使用 lapply()
函数将 ggpubr
包中的 ggqqplot
函数应用于 dat
的列 2:4:
library(tidyverse)
library(ggpubr)
vars <- paste0(names(dat[,2:5]))
lapply(vars, FUN=ggqqplot, data=dat)
这很好用,但我们想并排打印图形(例如,2 行 2 列)。我们如何使用应用框架来做到这一点?
ggqqplot
允许使用参数 facet_by
的分面(检查 ?ggqqplot
),因此您所要做的就是将数据转换为分面友好的长格式数据。见下文
dat_melt <- reshape2::melt(dat, measure.vars = vars) # converts data into long-form
ggqqplot(dat_melt, x="value", facet.by = "variable")
编辑:
如果你还想使用apply
功能,以下是我能想到的最简单的解决方案
plist <- lapply(vars, FUN = function (x) ggqqplot(dat,x = x))
cowplot::plot_grid(plotlist = plist, ncol = 2)
或管道友好的等价物
lapply(vars, FUN = function (x) ggqqplot(dat,x = x)) %>%
{cowplot::plot_grid(plotlist=.,ncol = 2)}
考虑以下数据框:
dat <- data.frame(
ID = c(1:200),
var1 = rnorm(200),
var2 = rnorm(200),
var3 = rnorm(200),
var4 = rnorm(200)
)
我们想使用 lapply()
函数将 ggpubr
包中的 ggqqplot
函数应用于 dat
的列 2:4:
library(tidyverse)
library(ggpubr)
vars <- paste0(names(dat[,2:5]))
lapply(vars, FUN=ggqqplot, data=dat)
这很好用,但我们想并排打印图形(例如,2 行 2 列)。我们如何使用应用框架来做到这一点?
ggqqplot
允许使用参数 facet_by
的分面(检查 ?ggqqplot
),因此您所要做的就是将数据转换为分面友好的长格式数据。见下文
dat_melt <- reshape2::melt(dat, measure.vars = vars) # converts data into long-form
ggqqplot(dat_melt, x="value", facet.by = "variable")
编辑:
如果你还想使用apply
功能,以下是我能想到的最简单的解决方案
plist <- lapply(vars, FUN = function (x) ggqqplot(dat,x = x))
cowplot::plot_grid(plotlist = plist, ncol = 2)
或管道友好的等价物
lapply(vars, FUN = function (x) ggqqplot(dat,x = x)) %>%
{cowplot::plot_grid(plotlist=.,ncol = 2)}