Skip to content

Instantly share code, notes, and snippets.

@potterzot
Last active August 4, 2016 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save potterzot/d2eb7a08c6cca7189faef47e02b56edb to your computer and use it in GitHub Desktop.
Save potterzot/d2eb7a08c6cca7189faef47e02b56edb to your computer and use it in GitHub Desktop.
Plotting with multiple library options in R

Plotting with Multiple Library Options in R

This is how I offer a single plot function with options to plot in different libraries. The motivation is that for research projects, sometimes we want an interactive graphic for web pages, but we might also want the same graphic in journal-quality png,svg,jpeg format.

It works well I think, but is there a better way of doing this?

The basic idea is a wrapper function that takes an argument that determines which plotting library to use, something like this:

#' Example plot for this question 
#' @export
#' 
#' @param ... functions passed to plot functions for specific engines. 
#' @param engine character determining which plotting engine to use.
ex_plot <- function(..., engine = c("ggplot", "plotly")) {
  engine <- match.arg(engine)
  p <- if(engine == "ggplot") { ex_plot.ggplot(...) }
       else if(engine == "plotly") { ex_plot.plotly(...) }
       else{ stop(paste("Engine", engine, "is not implemented for this plot.")) }
  p
}

Then I create a separate function for each library option. Here is the ggplot2 function:

#' Example plot using ggplot library. 
#' @export 
#' @import ggplot2
#' 
#' @rdname ex_plot 
#' @param d a data.frame or data.table. 
#' @param x the variable for the x axis. 
#' @param y the variable for the y axis. 
#' @return a ggplot object.
ex_plot.ggplot <- function(d, x, y) {
  x <- substitute(x)
  y <- substitute(y)
  ggplot(d) + geom_point(aes(x = eval(x), y = eval(y)))
}

And here is the plotly function:

#' Example plot using plotly library. 
#' @export 
#' @import plotly
#' 
#' @rdname ex_plot 
#' @param d a data.frame or data.table. 
#' @param x the variable for the x axis. 
#' @param y the variable for the y axis. 
#' @return a plotly object.
ex_plot.plotly <- function(d, x, y) {
  x <- substitute(x)
  y <- substitute(y)
  plot_ly(d, x = eval(x), y = eval(y), mode="markers")
}

Then to plot using two different libraries you can do something like the following:

### Example data and plots
d <- data.frame(a = 1:100,
                b = rnorm(100))
                
## Here we generate the ggplot version
p_ggplot <- ex_plot(d, x = a, y = b, engine = "ggplot")

## Here we generate the plotly version
p_plotly <- ex_plot(d, x = a, y = b, engine = "plotly")

GGPLOT

PLOTLY

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment