Skip to content

Instantly share code, notes, and snippets.

@wabarr wabarr/export_eps.R
Last active Mar 15, 2016

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

richfitz commented Mar 15, 2016

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

This comment has been minimized.

Copy link
Owner Author

wabarr commented Mar 15, 2016

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

@hadley

This comment has been minimized.

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

This comment has been minimized.

Copy link
Owner 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

This comment has been minimized.

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
You can’t perform that action at this time.