Plotting with R16 Sep 2015
In writing my signal error correction post (which I had saved as a draft and have since lost), I was looking for a nice diagram of a probability distribution function. I found this one on wikipedia:
This wasn’t quite what I wanted though. I was looking for a probability distribution for positive standard distributions; a probability distribution starting at zero. Luckily, I found some R code on the Wikimedia page, and set out to tweak it, ultimately producting this diagram:
I’m gonna give a breakdown of what the Wikipedia code did, and how I modified it to suit my needs. Let’s jump right in!
I changed the
filename here, for brevity.
This section of code is simple but tells us something important about R: There’s a script global scope. We call some command here to create a SVG, and then later we add to it and eventually write to a file.
This is a nifty feature of R scripts (and more generally, a lot of scripting languages). It keeps things short and simple.
par function sets parameters of a plot, and
mar represents the margins. Here we’re setting 2 “lines” of margin on the bottom and left.
Here there’s a
c function at work. From the docs:
This is a generic function which combines its arguments. The default method combines its arguments to form a vector
This is another cornerstone of R. Vectors, or one dimensional arrays. This is used a lot throughout this code sample; we’ll definitely see more of it.
Some shades of blue, light to dark, for us to use later. This also uses the
c function to create a vector.
Can you guess the return type of this? That’s right, a vector! R really like their vectors.
We can see another cool R feature here: The preference of named parameters. Named parameters are clean and concise. Reading this code we might not know yet what
"l" stand for, but we can clearly tell that they are settings for the type of the plot, the axes, and some
Using some online documentation, we can piece together what these parameters mean:
x, the first parameter, is the x coordinates of the points in the plot. Normally you’d have a
yparameter too, but we aren’t plotting any points here. These parameters are vectors!
typeis the plot type,
"n"means no plotting. We’re manually drawing on this, the plot acts as an empty canvas.
yaxsare values indicating the position of the axis, set either to
ylimindicate the bounding box of our view of the plot. Also passed in as vectors.
btymeans box type, and sets where lines are drawn around the plot. The values l, 7, c, u or ] all work, with l drawing the bottom and left lines.
yaxtindicate if the axis should be drawn or not. We set
"n", none, to avoid drawing that axis. We’ll manually draw it later.
ylabare the axis labels. We’re disabling those.