Skip to content

Instantly share code, notes, and snippets.

@thebioengineer
Created July 28, 2020 06:33
Show Gist options
  • Save thebioengineer/248e4b49446fdd354b10f0197e03f373 to your computer and use it in GitHub Desktop.
Save thebioengineer/248e4b49446fdd354b10f0197e03f373 to your computer and use it in GitHub Desktop.
provide tools for recording and then playing back tidytuesday plot generation! (Assumes you are using ggplot)
tt_recording_env <- new.env()
tt_record <- function(dir = tempdir(),
device = c("png", "jpeg", "bmp", "tiff", "emf", "svg", "eps"),
scale = 1,
width = NA,
height = NA,
units = c("in", "cm", "mm"),
dpi = 300,
limitsize = TRUE
){
if(!dir.exists(dir)){
dir.create(dir,recursive = TRUE)
}else{
if(length(list.files(dir) > 1)){
warning("Writing to a folder that already exists, and tt_playback may grab more files than intended!")
}
}
device <- match.arg(device)
units <- match.arg(units)
tt_recording_env$recording_dir <- dir
tt_recording_env$device <- device
## create shim function
tt_recording_env$print.view_and_save_ggplot <-
function(x,
newpage = is.null(vp),
vp = NULL,
...) {
# View plot
ggplot2:::print.ggplot(x, newpage = newpage, vp = vp, ...)
plot_file <- file.path(dir,paste0(format(Sys.time(), "%Y_%m_%d_%H_%M_%S"),".",device))
suppressMessages({
ggplot2:::ggsave(
filename = plot_file,
plot = x,
scale = scale,
width = width,
height = height,
units = units,
dpi = dpi,
limitsize = limitsize
)
})
invisible(x)
}
registerS3method(
genname = "print",
class = "ggplot",
method = "print.view_and_save_ggplot",
envir = tt_recording_env
)
}
tt_playback <- function(name = NULL,..., stoprecording = TRUE){
records <- list.files(
path = tt_recording_env$recording_dir,
pattern = paste0("*.",tt_recording_env$device,"$"),
full.names = TRUE)
if(is.null(name)){
recording <-
file.path(tt_recording_env$recording_dir,
paste0(format(Sys.time(), "%Y_%m_%d_%H_%M_%S"), ".gif"))
}else{
recording <- name
}
gifski::gifski(
records,
gif_file = recording,
...
)
viewer <- getOption("viewer", utils::browseURL)
if (is.function(viewer) && length(recording)) {
viewer(recording)
}
if(stoprecording){
registerS3method(
genname = "print",
class = "ggplot",
method = "print.ggplot",
envir = getNamespace("ggplot2")
)
}
invisible()
}
library(ggplot2)
tt_record(dir = "test_gg_record")
ggplot(data.frame(x = 1, y = 1)) + geom_point(aes(x,y)) + ylim(0,5)
ggplot(data.frame(x = 1, y = 2)) + geom_point(aes(x,y)) + ylim(0,5)
ggplot(data.frame(x = 1, y = 3)) + geom_point(aes(x,y)) + ylim(0,5)
ggplot(data.frame(x = 1, y = 4)) + geom_point(aes(x,y)) + ylim(0,5)
tt_playback()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment