Search code examples
rggplot2cowplot

Use variables supplied to aes_string() in other ggplot functions


I'm using aes_string() in a function to create some graphs. I'm using cowplot for theming and this scales the axes to the maximum values of the data provided, cutting off the top or side of the points at the maximum as in the example below.

I therefore want to add 5% to the max data for the column to add a little space. If I were not writing a function I could do something like

scale_y_continuous(expand = c(0,0), 
                       limits = c(0, max(y_var) *  1.05))

However, I don't know how to do this with aes_string(). Can anyone explain how to do this with aes_string()?

library(cowplot)
library(ggplot2)

fig_fun <- function(data, var){
  ggplot(data, aes_string(x = "wt", y = var)) + 
    geom_line() + 
    geom_point() +
    scale_y_continuous(expand = c(0,0), 
                       limits = c(0, NA))
}

data("mtcars")
p <- fig_fun(data = mtcars, var = "mpg")
p

current problem


Solution

  • You can extract the y variable from your data inside the expand_limits and scale that by 5%:

    expand_limits(y = c(0, max(data[, var])*1.05))
    

    Which makes:

    fig_fun <- function(data, var){
      ggplot(data, aes_string(x = "wt", y = var)) + 
        geom_line() + 
        geom_point() +
        expand_limits(y = c(0,max(data[, var])*1.05))) # picking the var column here
    }
    

    You will need an additional + scale_y_continuous(expand = c(0, 0)) to absolutely limit to those numbers.

    But as others suggested, if you use the default value for expand parameter of scale_y_continuous you'd get what you want. So scale_y_continuous(expand = c(0, 0.1)) would give you 10% extra space from your y axis boundaries on either side. Docs are here.

    The expand_limits method is still useful if you want some more custom solutions.