0

I am creating function which makes a ggplot. I need this function to add a ggtitle using the column name from which the data used for lotting came from.

the function is for the variable yvar and starts like this: scatter_plotseries <- function(yvar). yvar is essentially a list of values from a specific column: scatter_plots <- lapply(df[, c("D_x", "D_y", "D_z", "D_j", "D_k")], scatter_plotseries) I want the name of each plot to be called D_x or D_y etc.

different options I have tried within my ggplot:

  • ggtitle(as.character(colnames(df$yvar)))
  • ggtitle(as.character(names(df$yvar)))
  • ggtitle(as.character(colnames(df[, yvar])))
  • ggtitle(as.character(names(df[,yvar])))

I also tried something like this: names(df)[apply(df, 2, function(i) which(i == "D_x"))]

none of these options give the name of the specific column. they either return NULL or an error.

Please and thank you for the help!!

stefan
  • 90,330
  • 6
  • 25
  • 51
Juju
  • 1
  • 1
    Welcome to SO! It would be easier to help you if you provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a code example which others could run and snippet of your data or some fake data. – stefan Feb 22 '23 at 09:37
  • This said: Instead of looping over the columns of your df, loop over the column names so that these could be directly used in ggplot2. Doing so would require some minor adjustments of your plotting code, which however is not included in your post. – stefan Feb 22 '23 at 09:39

1 Answers1

0

Easiest is to loop over column names (e.g., plot 1):

Data frames are a special type of (named) list. It is actually quite a frequently desired feature to access the list names whilst looping, see for example Get names of list in for loop or Access names of list elements in a loop. Using the names for looping is generally the most straight forward way to go, but purrr::imap can access both element and name of a list (e.g., plot 2 ).

library(ggplot2)

## Plot 1: loop over names
ls_names <- names(mtcars)
ls_p <- lapply(ls_names, function(.x) {
  ggplot(mtcars[.x], aes(x = "x", y = .data[[.x]])) +
    geom_boxplot() +
    labs(title = .x, x = NULL)
})
patchwork::wrap_plots(ls_p)


## Plot 2: use purrr::imap
ls_p_imap <- purrr::imap(mtcars, function(.x, .y) {
  ggplot() +
    geom_boxplot(aes(x = "", y = .x)) +
    labs(y = .y, title = .y, x = NULL)
})
patchwork::wrap_plots(ls_p_imap)

Created on 2023-02-22 with reprex v2.0.2

tjebo
  • 21,977
  • 7
  • 58
  • 94