Home > Back-end >  Pass the ggplot2 title inside a function
Pass the ggplot2 title inside a function

Time:01-25

I need to specify a title that is determined by the column selected for a ggplot graph. I need to be able to make graphs for several of the columns in the data frame.

cola <- c(11, 13, 17, 12, 34)
colb <- c(23, 41, 32, 58, 26)
colc <- c(1, 2, 3, 4, 5)
dfb <- data.frame(cola, colb, colc)

library(ggplot2)
graph_func <- function(col) {
  dfb %>% ggplot(aes(x=colc, y=!!col))  
    geom_point()  
    ggtitle(title = !!col)
} 

graph_func(quo(colb))

I wanted the title to read 'colb' but I get an error message:

> Error in ggtitle(caption = !!col) : unused argument (caption = !!col)

CodePudding user response:

You do not need to quote the argument. Use !!enquo brackets {{ }} instead:

graph_func <- function(col) {
  dfb %>% ggplot(aes(x=colc, y= {{ col }}))  
    geom_point()  
    ggtitle(enquo(col))
} 

graph_func(colb)

CodePudding user response:

We can use deparse(substitute(`var`):

graph_func <- function(col) {
  dfb %>% ggplot(aes(x = colc, y = !!col))  
    geom_point()  
    ggtitle(deparse(substitute(col)))
}

graph_func(colb)

CodePudding user response:

We can use

library(ggplot2)
 graph_func <- function(col) {
  col <- rlang::as_string(rlang::ensym(col))
   dfb %>% ggplot(aes(x=colc, y=.data[[col]]))  
     geom_point()  
     ggtitle(col)
 }
graph_func(colb)
  • Related