r - gridsvg does not work when used inside a function -
i want define plot saving function uses gridsvg device package gridsvg.
library(ggplot2) library(gridextra) mtcars$gear <- factor(mtcars$gear,levels=c(3,4,5), labels=c("3gears","4gears","5gears")) mtcars$am <- factor(mtcars$am,levels=c(0,1), labels=c("automatic","manual")) mtcars$cyl <- factor(mtcars$cyl,levels=c(4,6,8), labels=c("4cyl","6cyl","8cyl")) myplot <- qplot(mpg, data=mtcars, geom="density", fill=gear, alpha=i(.5), main="distribution of gas milage", xlab="miles per gallon", ylab="density") saveplot <- function(filename, plot, plotwidth = 15, plotheight = 10){ gridsvg:::gridsvg(name = filename, width = plotwidth, height = plotheight) print(plot) dev.off(which = dev.cur()) }
however if try use function not work. error results:
saveplot("~/desktop/myplot.svg", myplot) show traceback rerun debug error in eval(expr, envir, enclos) : object 'filename' not found
however if steps console works:
gridsvg::gridsvg(name = "~/desktop/myplot.svg", width = 15, height = 10) myplot dev.off()
is there way might able use gridsvg function within function?
i wonder if might able eval environment.
thanks, ben.
here's roundabout, more principled, way without sticking in global environment (inspired scoping discussion in r inferno):
library(gridsvg) saveplot <- function(filename, plot, plotwidth = 15, plotheight = 10){ gridsvg(sys.frame(1)) print(plot) grid.export(filename) grdevices::dev.off(which = dev.cur()) }
sys.frame(1)
gives evaluation frame of parent context (there's ok explanation here variations on functions access call stack).
i separated out call grid.export()
call dev.off()
, because dev.off
gridsvg call grid.export
, call grdevices::dev.off
. lets explicitly feed file name grid.export
.
Comments
Post a Comment