Automate the Boring Stuff: GGPlot2

The majority of my interaction with the ggplot2 package involves the interactive execution of code to visualize data within the context of exploratory data analysis. This is often a manual process and quite laborious. I recently sought to improve these tasks by creating a series of user defined functions that contained my most commonly used ggplot calls. These functions could then be sourced in and the appropriate arguments specified to generate the desired visualization. While this is a fairly simple task, attempting to call ggplot2 functions within a user defined function requires some understanding of R’s evaluation procedures. The key thing to remember is that the generic aes mapping argument uses non-standard evaluation to specify variables names within ggplot. When programming, it is suggested that we utilize standard evaluation by using aes_string to map the properties of a geom. Here are some examples of how aes_string can be utilized within a function to create graphics.


library(ggplot2)

mydat <- data.frame(date = c(seq(as.Date("2010/01/01"), as.Date("2010/01/31"), by=1)),
                    value1 = abs(round(rnorm(31), 2)),
                    value2 = abs(round(rnorm(31), 2)),
                    value3 = abs(round(rnorm(31), 2)))

head(mydat)

viz_func <- function(data, x, y){
&nbsp;   ggplot(data, aes_string(x=x, y=y)) +
    geom_line(lwd=1.05) + geom_point(size=2.5) + 
    ggtitle("Insert Title Here") +
    xlab("Date") + ylab("Value") + ylim(0,5) + 
    theme(axis.text.x=element_text(colour="black")) +
    theme(axis.text.y=element_text(colour="black"))
}

viz_func(mydat, 'date', 'value1')

viz_func(mydat, 'date', 'value3') + 
  ggtitle("Insert Different Title Here") +
  xlab("Different Date") + ylab("Different Value")

viz_func <- function(data, x){
&nbsp;   ggplot(data, aes_string(x=x)) +
    geom_histogram() +
    ggtitle("Insert Title Here") +
    xlab("Date") + ylab("Value") + ylim(0,5) + 
    theme(axis.text.x=element_text(colour="black")) +
    theme(axis.text.y=element_text(colour="black"))
}

viz_func(mydat, 'value1')

viz_func(mydat, 'value3') + 
  ggtitle("Insert Different Title Here") +
  xlab("Different Date") + ylab("Different Value")