Dec 222010

It is well-known that R has several graphics devices — either the screen devices (X11(), windows(), …) or the off-screen devices (pdf(), png(), …). We can query the default graphics device in options():

getOption('device')

In a non-interactive session, the default device is pdf(). This is why Sweave has to create a file named Rplots.pdf no matter if you want it or not when you run Sweave on an Rnw file which has code chunks creating plots. Such a behaviour is annoying to me — the PDF file is not only unnecessary, but also time-consuming (creating this PDF file is completely a waste of time). Is there a way to set a “null” device? (like the /dev/null for *nix users) The answer is yes, but not so obvious. I have not found the device below documented anywhere:

options(device = function(...) {
    .Call("R_GD_nullDevice", PACKAGE = "grDevices")
})

This device can speed up Sweave a lot when there are many plots to draw. Here is a comparison:

x = rnorm(1000)
system.time({
    .Call("R_GD_nullDevice", PACKAGE = "grDevices")
    replicate(500, plot(x, pch = 1:21))
    dev.off()
})
#   user  system elapsed
#   1.51    0.02    1.53
system.time({
    pdf(file.path(tempdir(), "Rplots.pdf"))
    replicate(500, plot(x, pch = 1:21))
    dev.off()
})
#   user  system elapsed
#  47.81    0.20   48.10

One thing I don’t understand in Sweave is that it evaluates the code chunk twice if its Sweave options contain fig=TRUE. I think this might be a waste of time as well, and this is why I like pgfSweave, which has both the mechanism of caching R objects (using cacheSweave) and a smart way to cache graphics (using pgf).

WARNING: this null device may not work with plots that contain (math) expressions! (take a look at demo(plotmath) in case you do not know what are expressions in R graphics)

Mar 242010

Motivated by the excellent R package pgfSweave, I begin to notice the font families in my graphs when writing Sweave documents. The default font family for PDF graphs is Helvetica, which is, in most cases (I think), inconsistent with the LaTeX font styles. Some common font families are listed in ?postscript, and we can take a look at them by:

for (f in c("AvantGarde", "Bookman", "Courier", "Helvetica",
    "Helvetica-Narrow", "NewCenturySchoolbook", "Palatino", "Times")) {
    pdf.options(family = f)
    pdf(paste(f, ".pdf", sep = ""))
    set.seed(123)
    plot(rnorm(25), pch = 1:25, xlab = "xlab family", ylab = "ylab font",
        main = paste("Font Families in R (PDF):", f))
    text(13, 0, "Text in the Middle")
    mtext(sprintf("pdf.options(family = \"%s\")", f), side = 4)
    dev.off()
}

Here is a merged PDF containing the above single PDF files:

R-PDF-font-families.pdf (29K)

It seems that "Bookman", "NewCenturySchoolbook", "Palatino" and "Times" can be better choices when using Sweave because they are serif fonts, which are usually more consistent with LaTeX PDF.

Nov 112009

Since animation 1.0-9, we will be able to create a PDF document with an animation embedded in it; the function is saveLatex(), and its usage is similar to saveMovie() and saveSWF(): you pass an R expression for creating animations to this function, and this expression will be evaluated in the function; the image frames get recorded by a graphics device. In the end, a LaTeX document is written in a directory, and we can get a PDF document by running pdflatex on the document.

In fact, the key point is the LaTeX package named animate, which can be used to insert image frames into a PDF document to generate an animation. The interface of animations created by this package is quite similar to the HTML animation page by the R package animation, moreover, it also uses JavaScript (in PDF) to animate the image frames.

Oct 122008

I‘d like to thank Prof Michael Friendly for telling me this: just create a hyperlink to the file with the run protocol and then you can open a file directly from the hyperlink. For example, in LaTeX with hyperref package, you may use \href{run:path/to/some.file}{some link} to open this some.file in your PDF. This is a useful hack that I have been looking for over a long time.

Oct 022007
NOTE: There’s a typo in the graph! The \mu should be replaced with the sample mean \bar{x}! And the code is available in the R package animation; see library(animation); ?conf.int

Yihui @ Dec 24, 2007

Recently I’ve been thinking about attending the conference of IASC2008, and my vague idea is to use animations in statistical education, especially in the demonstration of some algorithms containing iterations or loops. Perhaps the main difficulty just lies in an integrated theory — currently I’m still not clear about the literature in this area (if anyone knows, please do drop me a line).

The other day when I was browsing the R documentation pages, I noticed that the amount of materials in those pages is increasing at a high speed. Among them I also saw some excellent web sites build by students (e.g. from Taiwan), which has triggered my own idea on building an independent website introducing animated pictures in statistics.

So… Let’s come back to the topic. In fact this is a demonstration I made several weeks ago, and today I modified it a little bit in order that the coverage rate can be better shown. The idea behind this simulation is simple: draw samples (random numbers) from the population which follows N(0, 1), and calculate confidence intervals (CI) based on these samples respectively. I believe everybody surely knows the formula in the main title of the figure below (suppose sigma is known, then compute the CI for the unknown mu). Here is an “animated” PDF file:

Downdload the file here

Demonstration of Confidence Intervals Using R

Sep 142007

There are many graphical functions offering the availability of the parameter alpha which is usually used to specify semi-transparent colors, however, such kind of colors can only be displayed in certain devices, as stated in the help of rgb():

Semi-transparent colors (0 < alpha < 1) are supported only on some devices: at the time of writing only on the pdf and (on MacOS X) quartz devices as well as several third-party devices such as those in packages Cairo, cairoDevice, JavaGD and RSvgDevice.

Here is an example illustrating semi-transparent colors in a pdf device:

WWW.YIHUI.NAME XIE@YIHUI.NAME © 2007 - 2012 by Yihui Xie