Friday, January 18, 2013

Using R to create visual illusions

This brings together two of my favorite (professional) things: R and visual illusions. Aside from being an extremely impressive application of R, it's a cool way of making it clear that the illusion is, in fact, an illusion. Here's a simple example:

library(grid)
grid.newpage()
grid.rect(c(1,3,1,3)/4, c(3,3,1,1)/4, 1/2, 1/2, 
          gp = gpar(col = NA, fill = gray(1:4/5)))
grid.rect(c(1,3,1,3)/4, c(3,3,1,1)/4, 1/6, 1/6, 
          gp = gpar(col = NA, fill = gray(0.5)))

Which creates the image below. The first call to grid.rect makes a set of four squares of different shades of gray, the second call inserts smaller squares inside those larger squares. The smaller squares are all the same shade of gray - which is obvious from the R code - but they appear to be different: the one in the upper left appears lightest and the one in the lower right appears darkest.