使用 lapply 将标签传递给 ggplot2

Using lapply to pass labels to ggplot2

我正在尝试使用 lapply 循环遍历包含绘图标签的向量列表。该列表包含矢量。向量的第一个元素是绘图标题,然后是 x 轴标签,然后是 y 轴标签。我想避免编写任何 for 循环。我不知道如何引用。下面的代码是我能想到的最接近的代码,但它只输出 NULL 3 次。

library(tidyverse)

plot.labels <- list(c("Title1","Xlab1","ylab1"),c("Title2","Xlab2","ylab1"),c("Title3","Xlab3","ylab1"))

plotter <- function(plotdata=d, xvar=cond,lab = NULL){
  ggplot(data = plotdata, aes( x = xvar , y = scale(vowmeanf0) ))+
    geom_point()+
    labs(title = lab[1],
         x = lab[2],
         y = lab[3])
}

lapply(plot.labels, function(x){
  for(df in 1:length(plot.labels)){
    plotter(x[df])
  }
} )

lapply should look more like this. You should never loop within lapply because lapply is essentially a wrapper for a for loop to begin with. lapply(plot.labels, function(x) plotter(plotdata = d, xvar = cond, lab = x)) – Mako212

有效

library(tidyverse)

plot.labels <- list(c("Title1","Xlab1","Ylab1"),c("Title2","Xlab2","Ylab2"),c("Title3","Xlab3","Ylab3"))

plotter <- function(plotdata = NULL, xvar = NULL ,lab = NULL){
  ggplot(data = plotdata, aes( x = xvar , y = scale(vowmeanf0) ))+
    geom_point()+
    labs(title = lab[1],
         x = lab[2],
         y = lab[3])
}

lapply(plot.labels, function(x) plotter(plotdata = d, xvar = "cond", lab = x))