I'm new to R and bio3d and have been unable to find any answers to my problem. I'm trying to find a way to save graphs/plots generated by bio3d (a R package). So far I have to manually click save as when the graph appears and I have tried many variations of R language to save the graph which either result in no saved file or a small file that cannot be opened. Can anyone give me some pointers please?
-
Did you search SO for questions with R and the pdf device? – IRTFM Jan 05 '15 at 21:11
-
Also the ?quartz page also describes a `quartz.save` function. – IRTFM Jan 05 '15 at 21:14
-
possible duplicate of [How to save a plot as image on the disk?](http://stackoverflow.com/questions/7144118/how-to-save-a-plot-as-image-on-the-disk) – Matt Parker Jan 06 '15 at 23:14
2 Answers
In an R script you may try with the following lines:
pdf('nameoftheplot.pdf', width=..., height=...)
Then you can write the R-code that generates your plot, and at the end you should add this last line:
dev.off()
Select all the lines and run them with cmd+R (Windows) or cmd+enter (OS X). The output pdf file with the plot should be located in your current working directory. Hope this works.
Edit: if you want a .png file as an output you have to replace the first line with:
png('nameoftheplot.pdf', width=..., height=..., res=...)
Edit2: Example:
pdf("firstplot.pdf", width=6, height=3)
qplot(carat, data = diamonds, geom = "density")
dev.off()

- 143
- 1
- 8
-
Hi, I've tried that and end up with Error in plot.new() : figure margins too large and Error in plot.xy(xy.coords(x, y), type = type, ...) : plot.new has not been called yet I don't quite understand the plot.new part. – Vron Jan 06 '15 at 10:27
-
That's strange... I've never had problems with the code I gave you above. I've done some researches and I found this link (http://stackoverflow.com/questions/23050928/error-in-plot-new-figure-margins-too-large-scatter-plot). Maybe you can try with the solution in the second answer... – ChicagoCubs Jan 06 '15 at 11:35
If you have already created your plot (i.e. it is displayed in the active quartz or x11 window) you can use dev.copy2pdf() and it relatives, e.g.
plot(c(1:10))
dev.copy2pdf(file="example.pdf")
If you want to do this without plotting to the quartz/x11 window then issue a call to png() or pdf() etc before your plot() call and then follow it with a dev.off() call, e.g.
pdf(file="example2.pdf")
plot(c(1:10))
dev.off()
The 'plot.new figure margins too large' error can occur when your plot window is too small to take all the graphic output you are trying to produce. Often making your window bigger will solve this.

- 26
- 1