Skip to content

Instantly share code, notes, and snippets.

@wabarr
Last active March 15, 2016 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wabarr/bf1a22abe0e26031b707 to your computer and use it in GitHub Desktop.
Save wabarr/bf1a22abe0e26031b707 to your computer and use it in GitHub Desktop.
simple function to export a plot to EPS, with possible options
## updated with input from @richfitz and @hadley - Thanks, guys!!
export_eps <- function(filename, expression, ...){
old <- setEPS()
on.exit(do.call(ps.options, old), add = TRUE)
postscript(filename, ...)
on.exit(dev.off(), add = TRUE)
expression
}
@richfitz
Copy link

Consider

export_eps <- function(filename, expression, ...){
  setEPS()
  postscript(filename, ...)
  on.exit(dev.off())
  eval(expression)
}

which will always close the device, even if expression fails.

@wabarr
Copy link
Author

wabarr commented Mar 15, 2016

Thanks @richfitz. I like this suggestion and have updated the gist.

@hadley
Copy link

hadley commented Mar 15, 2016

FWIW eval() isn't necessary here. This would be sufficient:

export_eps <- function(filename, expression, ...){
  setEPS()
  postscript(filename, ...)
  on.exit(dev.off())
  expression
}

You should also consider resetting the ps options:

export_eps <- function(filename, expression, ...){
  old <- setEPS()
  on.exit(do.call(ps.options, old), add = TRUE)

  postscript(filename, ...)
  on.exit(dev.off(), add = TRUE)

  expression
}

@wabarr
Copy link
Author

wabarr commented Mar 15, 2016

@hadley I don't understand why I don't need to eval() the expression. I guess I need to go read that section in Advanced R (more closely).

@leeper
Copy link

leeper commented Mar 15, 2016

Function arguments are lazily evaluated. So the plot expression won't actually be executed until it is called inside the function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment