Home > front end >  Dynamically change ggplot depending on the arguments passed to a function in R
Dynamically change ggplot depending on the arguments passed to a function in R

Time:04-20

I am currently writing a function which ultimately returns a ggplot. I would like to offer the user the option to change different aspects of that ggplot, such as the xlab by specifying it in the function. Right now I am using a code like this.

library(tidyverse)

d <- sample_n(diamonds,500)

plot_something <- function(data,x,y,x_axis_name=NULL){
  if(is.null(x_axis_name)){
    p<-ggplot(d,aes_string(x=x,y=y)) 
      geom_point()
  } else{
    p<-ggplot(d,aes_string(x=x,y=y)) 
      geom_point() 
      xlab(x_axis_name)
  }

  return(p)
}

plot_something(data=d, x="depth", y="price",x_axis_name = "random_name")

This works fine, but as you can see a lot of the code is duplicated, the only difference is the xlab argument. In this case it is not too bad, but my actual function is much more complicated and things get more difficult if I would also allow the user to for example modify the ylab.

So my question is, if there is a more elegant way to modify ggplots inside of a function depending on arguments passed by the user.

Any help is much appreciated!

CodePudding user response:

There is no need for the duplicated code. You could conditionally add layers to a base plot as desired like so:

library(tidyverse)

d <- sample_n(diamonds, 500)

plot_something <- function(data, x, y, x_axis_name = NULL) {
  x_lab <- if (!is.null(x_axis_name)) xlab(x_axis_name)

  p <- ggplot(d, aes_string(x = x, y = y))  
    geom_point()  
    x_lab

  return(p)
}

plot_something(data = d, x = "depth", y = "price", x_axis_name = "random_name")

Or using ggplot2s built-in mechanisms to choose defaults you don't even need an if condition but could do:

plot_something <- function(data, x, y, x_axis_name = ggplot2::waiver()) {
  p <- ggplot(d, aes_string(x = x, y = y))  
    geom_point()  
    xlab(x_axis_name)

  return(p)
}
  • Related