简体   繁体   中英

Separate plot titles within lapply

I have a number of objects which I would like to plot together on one page, with a separate title for each. At the moment, I have a vector of plot titles which I feed into ggtitle within lapply, but it adds only the first entry of this vector to each plot.

A quick and ugly minimal example is below:

library(ggplot2)
library(gridExtra)

#My 'data'
A.a <- rnorm(10)
A.b <- rnorm(30)
lmnames <- ls(pattern = "A.*")

titlenames <- c("Plot A", "Plot B")

plotlist <- list()
#I have a more complex ggplot function in reality, but I'm using qplot here as a placeholder.
plotlist <- lapply(lmnames, FUN=function(x,y){qplot(get(x)) + ggtitle(y)}, y=titlenames)

grid.arrange(grobs = plotlist)

It looks like this: 在lapply中使用ggtitle的不正确标题

You can see, both plots are labelled "Plot A". I'd like to have each plot labelled accordingly. Can anyone help me see what I'm missing here? Thanks in advance.

Your problem is, that in all your plots, your title is "Plot A" "Plot B", see plotlist[[1]]$labels$title .

A working code is the following:

plotlist <- lapply(1:length(lmnames), function(x){
  qplot(get(lmnames[x])) + ggtitle(titlenames[x])
})

I'm sure there are more elegant solutions. But this one will work.

Regards, J_F

Looping over multiple variables is often cleaner with mapply,

library(ggplot2)
library(gridExtra)

dl <- list("Plot A" = rnorm(10), "Plot B" = rnorm(10))
plot_fun <- function(x, y) qplot(x) + ggtitle(y)
grid.arrange(grobs = Map(plot_fun, x = dl, y = names(dl)))

在此处输入图片说明

This works fine:

plotlist <- lapply(1:2, FUN=function(i){qplot(get(lmnames[i])) + ggtitle(titlenames[i])})

Or this:

plotlist <- apply(data.frame(lmnames, titlenames), 1, FUN=function(x){qplot(get(x[1])) + ggtitle(x[2])})

在此处输入图片说明

The issue is that in both iteration, only the first value of y=titlenames is read in

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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