mythicalprogrammer
mythicalprogrammer

Reputation: 4737

ggplot2 programmically using aes_ and ..x../stat(x) return error

I want to turn this code:

library(ggplot2)
ggplot(mtcars, aes(x = cyl, fill = stat(x))) +
  geom_histogram(binwidth = 1) +
  scale_fill_gradient(low = 'blue', high = 'yellow')

into a function something like this:

library(ggplot2)
plotfn <- function (data, col_interest) {
  g <- ggplot(data, aes_(x = col_interest, fill = stat(x))) +
       geom_histogram(binwidth = 1) +
       scale_fill_gradient(low = 'blue', high = 'yellow')
  return(g)
}

plotfn(mtcars, "cyl")

I'd like to create a function for this and automate my code to reduce bugs and line counts but I don't know the equivalent ..x.. or stat(x) for aes_. The guide and notes on aes_ does not talk about this either.

Thanks.

Reference to stat(): https://ggplot2.tidyverse.org/reference/stat.html

Reference to aes_: https://ggplot2.tidyverse.org/reference/aes_.html

Upvotes: 0

Views: 91

Answers (1)

MrFlick
MrFlick

Reputation: 206167

If you want to pass in strings, then you would need to use rlang::sym and the !! (bang-bang) operator

library(ggplot2)
plotfn <- function (data, col_interest) {
  g <- ggplot(data, aes(x = !!rlang::sym(col_interest), fill = stat(x))) +
    geom_histogram(binwidth = 1) +
    scale_fill_gradient(low = 'blue', high = 'yellow')
  return(g)
}

or you can use the special .data variable

plotfn <- function (data, col_interest) {
  g <- ggplot(data, aes(x = .data[[col_interest]], fill = stat(x))) +
    geom_histogram(binwidth = 1) +
    scale_fill_gradient(low = 'blue', high = 'yellow')
  return(g)
}

plotfn(mtcars, "cyl")

With symbols you just use {{}}

plotfn <- function (data, col_interest) {
  g <- ggplot(data, aes(x = {{col_interest}}, fill = stat(x))) +
    geom_histogram(binwidth = 1) +
    scale_fill_gradient(low = 'blue', high = 'yellow')
  return(g)
}

plotfn(mtcars, cyl)

This way you leave the rest of the aes() unchanged to stat() continues to work.

Upvotes: 1

Related Questions