Since it is possible to export R plots to PDF or PNG or SVG etc., is it also possible to export an R plot to multiple formats at once? E.g., export a plot to PDF and PNG and SVG without recalculating the plot?
One option is to click on the 'Export' button in the 'Plots' tab in RStudio as we described previously. You can also export your plots from R to an external file by writing some code in your R script.
In most cases ggsave() is the simplest way to save your plot, but sometimes you may wish to save the plot by writing directly to a graphics device. To do this, you can open a regular R graphics device such as png() or pdf() , print the plot, and then close the device using dev. off() .
First, in order to save a plot as PDF in R you will need to open the graphics device with the pdf function, create the plot you desire and finally, close the opened device with the dev. off function.
Remember that your plot will be stored relative to the current directory. You can find the current directory by typing getwd() at the R prompt. You may want to make adjustments to the size of the plot before saving it. Consult the help file for your selected driver to learn how.
Without using ggplot2
and other packages, here are two alternative solutions.
Create a function generating a plot with specified device and sapply
it
# Create pseudo-data
x <- 1:10
y <- x + rnorm(10)
# Create the function plotting with specified device
plot_in_dev <- function(device) {
do.call(
device,
args = list(paste("plot", device, sep = ".")) # You may change your filename
)
plot(x, y) # Your plotting code here
dev.off()
}
wanted_devices <- c("png", "pdf", "svg")
sapply(wanted_devices, plot_in_dev)
Use the built-in function dev.copy
# With the same pseudo-data
# Plot on the screen first
plot(x, y)
# Loop over all devices and copy the plot there
for (device in wanted_devices) {
dev.copy(
eval(parse(text = device)),
paste("plot", device, sep = ".") # You may change your filename
)
dev.off()
}
The second method may be a little tricky because it requires non-standard evaluation. Yet it works as well. Both methods work on other plotting systems including ggplot2
simply by substituting the plot-generating codes for the plot(x, y)
above - you probably need to print
the ggplot object explicitly though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With