Tuesday, August 26, 2014

Pretty pictures with R

One of the nice things about using the R programming language, apart from the fact that it is free, is that it can produce beautiful graphics. As well as do all sorts of standard and non-standard plots and graphs, R can also generate animated GIF files.

For example, suppose we have some height:
\[h= exp( - \alpha r ) cos ( \beta \ r + p)\]
where r is the distance from the origin:
\[r=\sqrt{ x^2 + y^2 }\]
Also we have constants
\(\alpha\) which determines the decay
\(\beta\) determines the frequency
and \(p\) is the phase

We generate a matrix which we've called h. Each element corresponds to an x and a y.
We can convert that h matrix to an image and then cycle through values of phase to animate it. We will then have an image such as the one above.
Here is the R code that generates the h matrix:

Alternatively, we could also plot a spiral. The basic equation is:
\[r = exp( \phi \alpha + p ) \]
Where r is the distance from the origin, \(\phi\) is the angle to the x-axis, p is the phase and \(\alpha\) determines how tightly coilded it is.
We could of course plot such a path using a line chart in R. But it might be a bit more interesting to color it in. Again we could iterate through values of the phase p to generate an animated GIF file:

We could also build an RGB color triangle. Each corner is set to one of { red, green, blue }. That color then fades across the triangle until it is completely absent on the opposite edge.

Just in case you're interested, here's the full source code for the triangle: