Last active
June 24, 2022 21:18
-
-
Save eliocamp/4809150d06ec25ab04d35f963aaa5c0e to your computer and use it in GitHub Desktop.
Save a zip file with the data used to create each plot.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Define the directory where to save the plot data | |
knitr::opts_chunk$set(plot_data_dir = "plot-data2") | |
save_plot_data <- function(plot, label = "plot", dir = NULL) { | |
# If the user didn't set up a dir explicitly, don't do anything | |
if (is.null(dir)) { | |
return(invisible(NULL)) | |
} | |
if (!dir.exists(dir)) { | |
dir.create(dir) | |
} | |
# Build the ggplot2 plot. | |
gg <- ggplot2::ggplot_build(plot) | |
# Get the data of each layer into a list. | |
datas <- gg[["data"]] | |
# Get the name of the geom in each layer | |
geom_names <- vapply(gg[["plot"]][["layers"]], | |
function(x) class(x[["geom"]])[1], | |
FUN.VALUE = character(1) | |
) | |
geom_names <- make.unique(geom_names, sep = "_") | |
# Save the data of each label into its own file and | |
# zip them. | |
temp <- tempdir(TRUE) | |
files <- vapply(seq_along(datas), | |
function(l) { | |
file <- file.path(temp, paste0(geom_names[l], ".csv")) | |
write.csv(datas[[l]], file, row.names = FALSE) | |
file | |
}, | |
FUN.VALUE = character(1) | |
) | |
zipfile <- file.path(dir, paste0(label, ".zip")) | |
if (file.exists(zipfile)) { | |
file.remove(zipfile) # Need to remove previous versions of the data | |
} | |
zip(zipfile, | |
files = files, | |
flags = "-r9Xj" # To "flatten" the files | |
) | |
return(invisible(NULL)) | |
} | |
# Create the print method and register it. | |
# From https://bookdown.org/yihui/rmarkdown-cookbook/opts-render.html | |
knitr_print.gg <- function(x, options, ...) { | |
save_plot_data(x, options$label, options$plot_data_dir) | |
NextMethod("knitr_print") | |
} | |
registerS3method( | |
"knit_print", "gg", knitr_print.gg, | |
envir = asNamespace("knitr") | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment