R Notebook:在报告中嵌入图表并自动保存绘图文件
Great question! I’ve faced this exact issue before—knitr’s standard plot-saving options work perfectly for regular R Markdown reports, but they don’t translate cleanly to R Notebooks’ inline preview workflow. Here are two reliable solutions that I’ve used successfully:
1. Custom Wrapper Function (Most Flexible)
Build a simple function that first renders the plot inline for the Notebook, then saves it to your desired location. This works for both ggplot2 and base R plots:
For ggplot2 Plots
library(ggplot2) # Define a function to plot and save plot_and_save <- function(plot_object, save_path, ...) { print(plot_object) # Shows the plot inline in the Notebook ggsave(save_path, plot_object, ...) # Saves to disk with optional params (size, dpi, etc.) } # Example usage my_plot <- ggplot(mtcars, aes(x = mpg, y = hp, color = factor(cyl))) + geom_point(size = 2) # Display inline AND save as a PNG plot_and_save(my_plot, "mtcars_scatter.png", width = 7, height = 5, dpi = 300)
For Base R Plots
# Wrapper for base R graphics plot_and_save_base <- function(save_path, plot_expression, ...) { eval(plot_expression) # Render plot inline dev.copy(png, save_path, ...) # Copy the active plot to a file dev.off() # Close the graphics device to finalize the file } # Example usage plot_and_save_base( "iris_histogram.png", expression(hist(iris$Sepal.Length, col = "steelblue", main = "Sepal Length Distribution")), width = 600, height = 400 )
2. Knitr Hook (Auto-Save for All Plot Chunks)
If you want to avoid adding function calls to every plot, set up a knitr hook that automatically saves plots whenever you specify a save_plot chunk option. This preserves the Notebook’s inline preview while handling the save in the background:
# Set up the custom plot hook knitr::knit_hooks$set(plot = function(x, options) { # Keep the default inline plot display for R Notebook inline_output <- knitr::hook_plot_html(x, options) # If a save path is specified, copy the temp plot file to your target location if (!is.null(options$save_plot)) { file.copy(x, options$save_plot, overwrite = TRUE) } return(inline_output) })
Then use it in your code chunks like this:
# ```{r, save_plot="my_line_plot.png"} plot(mtcars$wt, mtcars$mpg, type = "l", lwd = 2, col = "darkred") # ```
Key Notes
- For base R plots with multiple graphs in one chunk, the hook will only save the last plot. Adjust the hook logic or use the wrapper function if you need to save multiple plots.
- Relative paths are relative to your R Notebook’s working directory (check with
getwd()if unsure). - Both methods let you control file formats (PNG, JPG, PDF, etc.) and output dimensions to match your needs.
内容的提问来源于stack exchange,提问作者Lauren Fitch

