Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate plot titles within lapply

Tags:

r

lapply

ggplot2

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: Incorrect titles using ggtitle in lapply

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.

like image 424
KerrBer Avatar asked Aug 02 '26 20:08

KerrBer


1 Answers

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

like image 107
J_F Avatar answered Aug 05 '26 09:08

J_F



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!