2

Suppose we wish to generate many plots and have them save (e.g in a loop or long script).

There are numerious *save* functions, many which appear to be specific to the type of plot/image being saved.

enter image description here

However, RStudio's Export > Save as Image seems very reliable and versatile, plus offers the ability to set the image format (from a drop down), and Width/Height, which is fantastic.

Is there a code equivalent of it (including the ability to select image type, hight and width)?

enter image description here

stevec
  • 41,291
  • 27
  • 223
  • 311
  • Does this answer your question? [How to save a plot as image on the disk?](https://stackoverflow.com/questions/7144118/how-to-save-a-plot-as-image-on-the-disk) – divibisan Apr 27 '20 at 18:22
  • 1
    `dev.print` from the accepted answer might be what you're looking for, since it accepts the device (pdf, png, jpg, etc.) as an argument – divibisan Apr 27 '20 at 18:25
  • @divibisan interesting. I definitely prefer to just use a single function. It means far fewer conditionals in code, and (even if this is not a great reason) it's a few fewer things to have to remember (i.e. it would be easy to look at available image formats with `?all_encompassing_save_fn` than have to recall all the available formats. I wlll look further into `dev.print` – stevec Apr 27 '20 at 18:27

1 Answers1

0

You can use this, similarfunctions exists for exporting in other formats.

pdf("filename.pdf", width=123, height=456)

plot()
...

dev.off()

Similar functions exists for exporting in other formats. such as bmp(), jpeg(), png(), and tiff()

Edit:

if you were looking to make a way to choose the filetype by variable you could implement this approach:

export.type <- "jpeg"
export.filename <- "plot1.jpeg"
export.height <- 123
export.width<- 123

export.func <- paste0(export.type,"(",export.filename,",height=",export.height,",width=",export.width,")")

eval(parse(text="export.func"))

you create a string of your function from variables, then evaluate it.

Daniel O
  • 4,258
  • 6
  • 20
  • Thanks. Is there one single more general function that accepts the image format as an argument? (rather than needing a separate function for each image format)? – stevec Apr 27 '20 at 18:18
  • 1
    @stevec not as you describe, but all those image formats take the same arguments for the most part. So you could just swap the function name. – Daniel O Apr 27 '20 at 18:24
  • @stevec I've added a "janky" way of accomplishing your goal. – Daniel O Apr 27 '20 at 18:35