title on a geom_qq plot

Hello,
how can I print the name of a vector (column) as the title on a plot using such a function:

oo <- function(x) {
  ggplot() + 
    aes(sample=x)+
    geom_qq() + 
    geom_qq_line(color="red")+
    labs(title=[..........])
}

lapply(mtcars, oo)

the plots turn up fine, but I need titles ("mpg" etc.)

It is probably better to not use lapply but a simple for-loop, or a loop like this:

oo <- function(i) {
  ggplot() + 
    aes(sample = mtcars[[i]])+ # double square brackets for getting the vector not a data frame
    geom_qq() + 
    geom_qq_line(color="red")+
    labs(title=names(mtcars)[i])
}

map(1:length(mtcars), oo) # the map function from purrr package, similar to lapply

Thanks for your reply. Your method does what's needed, however I wanted to avoid defining dataframe inside the function to make it more universal, so that I could supply it with other dataframes (or different subsets of a larger dataframe).

I thought that lapply supplies vector (i.e. a column of a dataframe) to the function, so it could take the name of the vector as a title. I have not figured out how to get to that name, though. Guess I am wrong here..

Maybe define a function with two arguments? e.g. oo <- function(dataset, i) {...}

I replaced lapply with map because I found that lapply didn't take the 1:length(mtcars) vector. Essentially, both functions are alternative forms of a simple for-loop. There is a names function for getting the names of all variables in the dataframe mtcars, but, unfortunately, it only works for the dataframe object but not each variable in the dataframe. Good luck!

A little trick using purrr::map2() instead of lapply()

library(ggplot2)
library(purrr)

map2(mtcars, names(mtcars),
     ~{ ggplot() + 
             aes(sample = .x) +
             geom_qq() + 
             geom_qq_line(color = "red") +
             labs(title = .y)
     }
)
#> $mpg

#> 
#> $cyl

#> 
#> $disp

#> 
#> $hp

#> 
#> $drat

#> 
#> $wt

#> 
#> $qsec

#> 
#> $vs

#> 
#> $am

#> 
#> $gear

#> 
#> $carb

Created on 2020-09-26 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.