rggplot2expss

EXPSS labels in a ggplot called from a function


I'm struggling combining the use of variables' labels (provided by the expsspackage) in a ggplot2plot from a function I've written to repeat it several times. In other words, the following code works as expected.

data(mtcars)
library(expss)
library(ggplot2)

mtcars <- apply_labels(mtcars,
                   mpg = "MPG",
                   cyl = "CYL",
                   wt = "WEIGHT")

use_labels(mtcars, {
    # from the example of the package's vignette
    ggplot(..data) +
        geom_point(aes(y = mpg, x = wt))
}) 

If I want to write a function like

myplot <- function(x,y) {
     ggplot(data=mtcars) +
        geom_point(aes(y = {{y}}, x = {{x}}))
}

myplot(mpg, cyl)
myplot(mpg, wt)

This works as appropriate as well.

But if I use

myplot <- function(x,y) {
     use_labels(data=mtcars, { 
     ggplot(..data) +
        geom_point(aes(y = y, x = x))
  })
}

myplot("mpg", "cyl")

This does not work anymore, i.e. the plot is not correct and the labels are not shown.

I've tried

myplot <- function(x,y) {
     use_labels(data=mtcars, { 
     ggplot(data=mtcars) +
        geom_point(aes(y = mtcars[[y]], x = mtcars[[x]]))
  })
}

myplot("mpg", "cyl")

Then the plot is correct, but the labels are not shown...


Solution

  • Much easier solution: the ggeasy package (https://rdrr.io/cran/ggeasy/man/easy_labs.html)

    The following works perfectly:

    myplot <- function(x,y) {
         ggplot(data=mtcars) +
            geom_point(aes(y = {{y}}, x = {{x}}))+
            ggeasy::easy_labs(teach=TRUE)
    }
    
    myplot(mpg, cyl)