简体   繁体   English

使用lapply将标签传递给ggplot2

[英]Using lapply to pass labels to ggplot2

I am trying to use lapply to loop through a list of vectors containing plot labels. 我正在尝试使用lapply遍历包含绘图标签的向量列表。 The list contains vectors. 该列表包含向量。 The first element of the vector is the plot title, then the x axis label, and then the y axis label. 向量的第一个元素是绘图标题,然后是x轴标签,然后是y轴标签。 I want to avoid writing any for loops. 我想避免编写任何for循环。 I can't figure out how to reference the. 我不知道如何引用。 The code below is the closest I could come up with, but it just outputs NULL 3 times. 下面的代码是我能想到的最接近的代码,但是它只输出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. lapply应该看起来更像这样。 You should never loop within lapply because lapply is essentially a wrapper for a for loop to begin with. 绝对不要在lapply中循环,因为lapply本质上是for循环的包装器。 lapply(plot.labels, function(x) plotter(plotdata = d, xvar = cond, lab = x)) – Mako212 lapply(plot.labels,function(x)绘图仪(plotdata = d,xvar = cond,lab = x))– Mako212

That worked 那工作

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM