how to add a coord_flip argument to a function embedding a ggplot graph

Viewed 113

I have a simple function wrapping a ggplot graph :

library(ggplot2)
  myGraph <- function(data,x,y) {
  ggplot(data, aes_string(x=x,y=y,group=1) +
  geom_line() %>%
  return()
}

And I would like to add an argument to the function so that I can flip the axes, or not. a boolean which, if it is true, add a line

coord_flip() +

to the code.

3 Answers

This could be achieved like so:

library(ggplot2)
myGraph <- function(data,x,y, flip = FALSE) {
  flip <- if (flip) coord_flip()
  
  ggplot(data, aes_string(x=x,y=y,group=1)) +
           geom_line() +
           flip
}

myGraph(mtcars, "hp", "mpg", TRUE)

It's nice to be able to pass unquoted column names to a ggplot function, so you could do:

myGraph <- function(data, x, y, flip = FALSE) {
  x <- enquo(x)
  y <- enquo(y)
  p <- ggplot(data, aes(x = !!x , y = !!y, group = 1)) + geom_line()
  if(flip) return(p + coord_flip())
  return(p)
}

So that you can have:

myGraph(mtcars, mpg, cyl)

enter image description here

myGraph(mtcars, mpg, cyl, flip = TRUE)

enter image description here

Try this approach using a new parameter in your function that enables the flip option:

library(tidyverse)
#Function
myGraph <- function(data,x,y,change=0){
  if(change==0){
    G1 <- ggplot(data, aes_string(x=x,y=y,group=1)) +
                   geom_line()
  } else
  {
    G1 <- ggplot(data, aes_string(x=x,y=y,group=1)) +
                   geom_line()+
                   coord_flip()
  }
  return(G1)
}
#Apply 2
myGraph(iris,x = 'Species',y = 'Sepal.Width',change = 0)
myGraph(iris,x = 'Species',y = 'Sepal.Width',change = 1)

Outputs:

enter image description here

enter image description here

Related