R Configurable Output Device

The device function auto-increments the filename, and can be configured with option(nj.dev ="<dev>") to svg, png, or jpeg.

..nj <- new.env(parent=emptyenv())
..nj$n.out <- 0

nj.output <- function(filename) {
  if (missing(filename)) {
    n.out <- get("n.out", envir=..nj)
    filename <- paste0("/results/out-",n.out)
    n.out <- n.out + 1
    assign("n.out", value=n.out, envir=..nj)
  }
  if (getOption("nj.output.verbose")) cat(sprintf("Creating %s\n", filename))
  
  dev <- getOption("nj.output.dev")
  wd <- getOption("nj.output.width")
  ht <- getOption("nj.output.height")
  fs <- getOption("nj.output.fontsize")
  bgc <- getOption("nj.output.bg")
  switch(dev,
    svg=,SVG={
      wd <- wd %/% 72
      ht <- ht %/% 72
      svg(paste0(filename,".svg"), onefile=TRUE, 
          bg=bgc, width=wd, height=ht, 
          pointsize=fs, family="sans", antialias="subpixel")
    },
    jpg=,JPG=,jpeg=,JPEG={
      jpgQ <- options("nj.output.jpgQ")
      jpeg(paste0(filename,".jpg"), quality=jpgQ, 
           bg=bgc, width=wd, height=ht, units="px", 
           pointsize=fs, family="sans", antialias="subpixel")
    },
    png=,PNG={
      png(paste0(filename,".png"), 
          bg=bgc, width=wd, height=ht, units="px", 
          pointsize=fs, family="sans", antialias="subpixel")
    },
    {
      print("Invalid default Nextjournal output device.")
    })
}

options(device = "nj.output")

# set defaults
options(nj.output.dev = "svg")
options(nj.output.width = 800)
options(nj.output.height = 600)
options(nj.output.fontsize = 12)
options(nj.output.jpgQ = 95)
options(nj.output.bg = "white")
options(nj.output.verbose = TRUE)
attach(iris)

# Default SVG
plot(Petal.Length, Petal.Width,
     main="Iris Data",
     xlab="Iris petal length",
     ylab="Iris petal width"
    )
abline(lm(Petal.Width~Petal.Length), col="red")
lines(lowess(Petal.Length,Petal.Width), col="blue")
dev.off()

# JPEG
options(nj.dev = "jpeg")
pairs(~Sepal.Length+Sepal.Width+Petal.Length+Petal.Width, data=iris,
      main="Scatterplot Matrix"
     )
dev.off()

# And PNG
options(nj.dev = "png")
p1 <- hist(rnorm(500,4), breaks=25)
p2 <- hist(rnorm(500,6), breaks=25)
plot(p1, col=rgb(0,0,1,0.25), xlim=c(0,10))
plot(p2, col=rgb(1,0,0,0.25), xlim=c(0,10), add=T)
dev.off()

detach(iris)
© 2018 Nextjournal GmbH