I'm trying to figure out how to make a variable call to facet_wrap within a ggplot2 function.
Ideally I want this within the body of the function.
I can't install the github version of reprex, hopefully the code below renders OK, apologies if not.
There's a bit of data prep to get some suitable time series data , a manual plot function that works if I give it the extra commands outside of the function (which I want to avoid), and then my current failed attempt.
In addition to trying quote(group_var)
, I've also tried as.name()
and eval()
library(tidyverse)
data <- list(fdeaths,mdeaths,ldeaths) #time series data- needs prep
names(data)[1:3] <- c("fdeaths","mdeaths","ldeaths")
data <- as_tibble(data)
startdate <- as.Date('1974-1-1')
data$date <- seq.Date(startdate,by = 'month',length.out = 72)
newdata <- tidyr::gather(data, key = key, value = value,-date)
newdata$value <- as.numeric(newdata$value)
manual_facet_plot <- function(df, datecol, y_var,...){
p <- ggplot2::ggplot(df,ggplot2::aes_(substitute(datecol),substitute(y_var))) +
ggplot2::geom_line(colour = "grey40", group = 1) +
ggplot2::geom_point(colour = "grey40", na.rm = TRUE)
p
}
#now with grouping_variable
fail_plot <- function(df, datecol, y_var, group_var,...){
p <- ggplot2::ggplot(df,ggplot2::aes_(substitute(datecol),substitute(y_var))) +
ggplot2::geom_line(colour = "grey40", group = 1) +
ggplot2::geom_point(colour = "grey40", na.rm = TRUE) +
ggplot2::facet_wrap(. ~ quote(group_var), ncol = 3)
p
}
This works - but I want the facet_wrap call inside the function
manual_facet_plot(newdata,date,value) +
facet_wrap( ~ key, ncol = 3)
This fails miserably:
fail_plot(newdata,date,value,key)
I have many more lines of code to add to the final plot but I can't seem to figure this out.
I've looked at http://rpubs.com/hadley/97970 but I'm not seeing how to tweak the facets accordingly.
Any help appreciated
thanks
John