Search code examples
rggplot2plyr

Aesthetics and bang-bang in ggplot2


I am trying to write a function that creates a barplot but I have trouble getting the fill aesthetic right.

  • If I use fill = !!x leads to Quosures can only be unquoted within a quasiquotation context.
  • and fill = x leads to Aesthetics must be either length 1 or the same as the data (4): fill

My Code:

genBar <- function(data, x, y) {
  x <- enquo(x)
  y <- enquo(y)
  plot <- ggplot(data) +
    geom_bar(aes(!!x, !!y),
             stat = 'identity',
             fill = <help>) 
  return(plot)
}

Solution

  • fill should be inside aes. Try :

    library(ggplot2)
    
    genBar <- function(data, x, y) {
      plot <- ggplot(data) +
        geom_bar(aes({{x}}, {{y}}, fill = {{x}}),
                 stat = 'identity') 
      return(plot)
    }
    
    genBar(mtcars, cyl, mpg)
    

    If you want to pass column names as string use .data pronoun.

    genBar <- function(data, x, y) {
      plot <- ggplot(data) +
        geom_bar(aes(.data[[x]], .data[[y]], fill = .data[[x]]),
                 stat = 'identity') 
      return(plot)
    }
    
    genBar(mtcars, "cyl", "mpg")