Home > other >  Ggplot2 title inside a function(x)
Ggplot2 title inside a function(x)

Time:01-24

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)

  • Related