Skip to content

Instantly share code, notes, and snippets.

@gadenbuie
Forked from EmilHvitfeldt/plot-it-all.R
Created October 18, 2018 02:54
Show Gist options
  • Save gadenbuie/8e442cdf661917ddfa0de75daef97e4b to your computer and use it in GitHub Desktop.
Save gadenbuie/8e442cdf661917ddfa0de75daef97e4b to your computer and use it in GitHub Desktop.
Plot every since ggplot2 plot
library(ggplot2)
directory <- "~/Desktop/dataviz/"
fs::dir_create(directory)
print.ggplot <- function(x, newpage = is.null(vp), vp = NULL, ...) {
set_last_plot(x)
if (newpage) grid::grid.newpage()
# Record dependency on 'ggplot2' on the display list
# (AFTER grid.newpage())
grDevices::recordGraphics(
requireNamespace("ggplot2", quietly = TRUE),
list(),
getNamespace("ggplot2")
)
data <- ggplot_build(x)
gtable <- ggplot_gtable(data)
if (is.null(vp)) {
grid::grid.draw(gtable)
} else {
if (is.character(vp)) seekViewport(vp) else pushViewport(vp)
grid::grid.draw(gtable)
upViewport()
}
ggsave(paste0(directory, Sys.time(), ".png"), plot = x)
invisible(x)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment