rfunctionggtern

ggtern custom function object x not found error


I'm trying to create a custom function that draws a ternary plot using the package ggtern

Here is an example of the data and the function

library(tidyverse)
library(ggtern)

myData <- tibble(T_x = c(0.461, 0.778, 0.429),
             T_y = c(0.126, 0.108, 0.404),
             T_z = c(0.413, 0.114, 0.167))

drawTriad <- function(df, x, y, z) {
  x <- enquo(x)
  y <- enquo(y)
  z <- enquo(z)
  df %>% 
    ggtern::ggtern(aes(!!x,
                       !!y,
                       !!z)) +
    geom_point(size = 2, color = "blue") +
    theme_void() + 
    theme_hidelabels() +
    theme(tern.axis.line = element_line(color='darkgray',size=1.5))
}

When I run the function on myData like this:

drawTriad(myData, T_x, T_y, T_z)

I'm getting the following error: Error in FUN(X[[i]], ...) : object 'x' not found

How can I get this simple function to work?


Solution

  • A couple of options...

    library(ggplot2)
    library(magrittr)
    library(tibble)
    library(ggtern)
    

    Option 1

    This is simpler: just rename the variables in the source data frame or tibble to suit ggtern, this avoids the issue of programmatic variables for the point coordinates.

    drawTriad <- function(df) {
      df %>% 
        ggtern::ggtern(aes(x, y, z)) +
        geom_point(size = 2, color = "blue") +
        theme_void() + 
        theme_hidelabels() +
        theme(tern.axis.line = element_line(color='darkgray',size=1.5))
    }
    
    drawTriad(myData)
    

    Option 2

    This is based on the explanation given in ggplot2: elegant graphics for data analysis https://ggplot2-book.org/programming.html. And matches the problem set out in the question.

    drawTriad <- function(df, x, y, z) {
    
      df %>% 
        ggtern::ggtern(aes_(x = as.name(x), y = as.name(y), z = as.name(z))) +
        geom_point(size = 2, color = "blue") +
        theme_void() + 
        theme_hidelabels() +
        theme(tern.axis.line = element_line(color='darkgray',size=1.5))
    }
    
    drawTriad(df = myData,
              x = "T_x",
              y = "T_y",
              z = "T_z")
    

    Created on 2021-12-13 by the reprex package (v2.0.1)