Helen
Helen

Reputation: 63

R- pass argument to ggplot in function

I have a question about how to pass an argument to ggplot if I want to have a 1-x x-axis. The function is being used to specify column name in my data frame.

Let's say my data frame looks like

x1    x2    x3   x4
0.1   0.2   0.3  0.4
0.3   0.5   0.7  0.9
0.4   0.6   0.8  0.2     

And I have a function

myfunction<- function(x, y, convert = False){

if (flip) {
  ggplot(data = mydata, aes(x=1-get(x), y=get(y))) + geom_line() + 
  xlab(x) + ylab(y)
    } else {
  ggplot(data = mydata, aes(x=get(x), y=get(y))) + geom_line() + 
  xlab(x) + ylab(y)
    }
}

It works when convert = False, but if I want to plot myfunction(x1, x2, convert = TRUE), my x-lab is still "x1", not "1-x1". I have tried to code xlab(1-get(x)) but it doesn't work. Anyone have an idea about how to print x-label as "1-x1", where x1 is a column name in a data frame?

Upvotes: 1

Views: 1435

Answers (1)

akrun
akrun

Reputation: 886938

Based on the function arguments, it seems like convert is flip. Instead of using get to modify the 'x' argument, we can do this with mutate after converting the arguments to quosures

myfunction<- function(mydata, x, y, convert = FALSE){
    x <- enquo(x)
    y <- enquo(y)
    xnew <- quo_name(x)
if (convert) {
   mydata %>%
         mutate(!! (xnew) := 1- !!(x)) %>%
         ggplot(., aes_string(xnew, quo_name(y))) +
               geom_line() + 
               xlab(paste0("1 - ", xnew))
   
} else {

     ggplot(mydata, aes_string(xnew, quo_name(y))) +
             geom_line()

    }
    
}

myfunction(df1, x1, x2, convert = TRUE)

-output

enter image description here

myfunction(df1, x1, x2, convert = FALSE)

-output

enter image description here

data

df1 <- structure(list(x1 = c(0.1, 0.3, 0.4), x2 = c(0.2, 0.5, 0.6), 
x3 = c(0.3, 0.7, 0.8), x4 = c(0.4, 0.9, 0.2)), .Names = c("x1", 
"x2", "x3", "x4"), class = "data.frame", row.names = c(NA, -3L
))

Upvotes: 1

Related Questions