Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a command to export the current plot?

Tags:

plot

r

ggplot2

I'm creating a whole mess of charts, and would like to export the produced charts as PDF. It's possible to click 'export' in the Plot tab in rstudio and manually select "save plot as PDF", of course, and I'd prefer not to wrap every single one of my sections in pdf() / dev.off().

Ideally I'd like a function that would take the currently-displayed plot in RStudio and save it with the parameters I'd like (format /filename / width / height).

Thoughts?

Update

As per @naught101's suggestion - for a 5x7 (inch!) pdf file which is a convenient size to be pasted into an A4 Word document, the following works well:

dev.copy2pdf(file="example.pdf", width = 7, height = 5)

Better yet, as an easily-called function with default dimensions:

dopdf <- function(filename = "dopdf.pdf", pdf.width = 7, pdf.height = 5) {
 dev.copy2pdf(file=filename, width = pdf.width, height = pdf.height)
}

While using ggplot2 would have let me save using the ggsave function, dev.copy2pdf is a good generic solution (answering my original question).

like image 631
Simbamangu Avatar asked May 08 '12 10:05

Simbamangu


People also ask

How do I Export a plot in R?

Plots panel –> Export –> Save as Image or Save as PDF It's also possible to save the graph using R codes as follow: Specify files to save your image using a function such as jpeg(), png(), svg() or pdf(). Additional argument indicating the width and the height of the image can be also used.

Which command is used to plot a graph?

The plot() function in R is used to create the line graph.


1 Answers

I think you're looking for dev.copy2pdf. This allows you to copy the current device to a pdf, using the same arguments as pdf(). Works just as well for the base plotting functions as for ggplot2, (and any other plotting libraries that use the standard grDevice plotting devices, by the looks of it).

like image 160
naught101 Avatar answered Oct 19 '22 02:10

naught101