使用lapply将标签传递给ggplot2 [英] Using lapply to pass labels to ggplot2
问题描述
我正在尝试使用lapply遍历包含绘图标签的向量列表.该列表包含向量.向量的第一个元素是绘图标题,然后是x轴标签,然后是y轴标签.我想避免编写任何for循环.我不知道如何引用.下面的代码是我能想到的最接近的代码,但它只会输出 NULL
3次.
I am trying to use lapply to loop through a list of vectors containing plot labels. 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. I want to avoid writing any for loops. 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.
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应该看起来更像这样.绝对不要在lapply中循环,因为lapply本质上是for循环的包装器.lapply(plot.labels,function(x)绘图仪(plotdata = d,xvar = cond,lab = x))– Mako212
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))
这篇关于使用lapply将标签传递给ggplot2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!