R Graphics

Data visualization, statistical animations, graphical demos and examples with R

Apr 172010
A new paper on the α-convex hull appeared in the Journal of Statistical Software today (http://www.jstatsoft.org/v34/i05/paper). The α-convex hull is an interesting problem which caught my attention long time ago but I didn’t know a solution then. R has a function chull() which can generate (indices of) the convex hull for a series of points. Now we can use the R package alphahull to compute the α-convex hull. For those who are not familiar with the α-convex hull, the animation below might be a good illustration for the difference between a convex hull and an α-convex hull. Note how the parameter α affects the shape of the hull:

alpha-convex hull with different alpha's

alpha-convex hull with different alpha's

The above animation can be reproduced with the code below (uncomment the lines to create a GIF animation with the animation package):

Apr 032010

We know the real distribution of the F statistic in linear models — it is a non-central F distribution. Under H0, we have a central F distribution. Given 1 – α, we can compute the probability of (correctly) rejecting H0. I created a simple demo to illustrate how the power changes as other parameters vary, e.g. the degrees of freedoms, the non-central parameter and alpha. Here is the video:

The Power of F Test

And for those who might be interested, here is the code (you need to install the gWidgets package first and I recommend the RGtk2 interface). Have fun:

Mar 242010
Amber Watkins gave me a suggestion on the animation for the ratio estimation, and I think this is a good topic for my animation package. I’ve finished writing the initial version of the function sample.ratio() for this package, which will appear in the version 1.1-2 a couple of days later.

As we know, the benefit of ratio estimation is that sampling skewness may be adjusted for, because the estimation of \bar{Y} will make use of the information in the relationship of X and Y: \bar{X} \cdot (\bar{y}/\bar{x}). Here is a demo (we can see the ratio estimate, denoted by the red line, generally performs better than \bar{y}):

An animation demo for the ratio estimation

An animation demo for the ratio estimation

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.

Mar 232010

Here are some (trivial) R tips in the course Stat 511. I’ll update this post till the semester is over.

  1. Formatting R Code

  2. I’ve submitted an R package named formatR to CRAN yesterday. This package should be easier than the code below, because there is a GUI to tidy your R code. Install with install.packages('formatR').

    Reading code is pain, but the well-formatted code might alleviate the pain a little bit. The function tidy.source() in the animation package can help us format our R code automatically. By default it will read your code in the clipboard, parse it and return the well-formatted code. You have options to keep or remove the comments/blank lines and set the width of the code, etc. Spaces and indent will be added automatically. This can save us time typing spaces and paying attention to indent.

    ## install.packages('animation') if it is not installed yet
    library(animation)
    ## copy some R code somewhere and type:
    tidy.source()
    ## or specify the path of your code file
    tidy.source(file.path(system.file(package = "graphics"), "demo", "image.R"))
    ## can also use a URL
    tidy.source('http://www.public.iastate.edu/~dnett/S511/twofactor.R')
    ## remove blank lines
    tidy.source('http://www.public.iastate.edu/~dnett/S511/twofactor.R',
               keep.blank.line = FALSE)
    ## remove comments
    tidy.source('http://www.public.iastate.edu/~dnett/S511/twofactor.R',
               keep.comment = FALSE)
    
Dec 312009

I have to admit that the previous post on Christmas is actually not much fun. Today I received another pResent from Yixuan which is more interesting:

Dec 242009

Life should be fun. I saw a post in R-help list saying Merry Christmas to other useRs, and I followed up by some R code which can produce a naive animation like this:

Here is the code to generate the above Flash animation with shining Christmas:

library(animation)
saveSWF({
    n = length(speed <- runif(angle <- runif(x <- strsplit("MERRY CHRISTMAS",
        "")[[1]], 0, 360), 0, 15))
    for (j in 1:300) {
        angle = angle + speed
        plot.new()
        plot.window(c(1, n), c(0, 1))
        for (i in 1:n) text(i, 0.5, x[i], srt = angle[i], cex = runif(1,
            1, 4), col = sample(colors(), 1))
        text(n, 0, "Yihui @ 2009-12-24 (http://yihui.name)",
            adj = c(1, 0), col = "white", cex = 0.8)
    }
}, interval = 0.04, dev = "pdf", outdir = getwd(), para = list(mar = rep(0,
    4), bg = "black"), width = 8, height = 1)
## in animation package (>=1.1-0), see demo('Xmas')

There are other animation formats in the R package animation:

  1. use saveMovie() to get a GIF animation (need ImageMagick)
  2. ani.start() and ani.stop() can produce an HTML page with the animation in it
  3. saveLatex() can embed an animation into a PDF document
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 102009

Today Romain Francois posted an interesting topic in the R-help list, and you can read his blog post for more details: celebrating R commit #50000. 50000 is certainly not a small number; we do owe R core members a big “thank you” for their great efforts in this fantastic statistical language in the 13 years. When I saw Romain’s data, I suddenly remembered a question I asked to one of Prof Ripley’s student a couple of years ago: does Prof Ripley ever sleep? And he answered “No!”. No wonder we can see Prof Ripley so frequently in the R-help/devel mailing list. If you have stayed on R-help list for enough long time, you’ll surely know several facts, e.g. Martin Maechler will arrive in less than 3 minutes if you dare call an R package “library”, and you will get “Ripleyed” if you are not careful enough in posting your R code.

> library(fortunes)
> fortune("Ripleyed")

And the fear of getting Ripleyed on the mailing list also makes me think, read,
and improve before submitting half baked questions to the list.
 -- Eric Kort
 R-help (January 2006)
Jun 122009
Linlin Yan posted a cool (hot?) simulation of burning fire with R in the COS forum yesterday, which was indeed a warm welcome. I’m not sure whether our forum members will be scared by the “fire” under the title “Welcome to COS Forum”. :grin: The fire was mainly created by the function image() with carefully designed rows and columns in heated colors heat.colors(). Here is one of the pictures generated from his code:

Simulation of Burning Fire in R

Simulation of Burning Fire in R

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