In this post we’ll cover go into more detail on plotting commands. We’ll use a scatterplot (X-Y plot) as our example plot. Again we’ll use the command plot.
Next let’s change the axis labels. To change the axis titles we’ll use the commands xlab and ylab for the x-axis and y-axis, respectively. We add these calls within the parenthesis of the plot function. Let’s make the x-axis “Even” and the y-axis “Odd”.
Looks good! Now let’s change the x- and y-axis limits. We’ll use the commands xlim and ylim. In each case we give a lower and upper limit, so we need to concatenate them together with the c function. In our example we’ll set the x-axis from 0 to 15 using xlim = c(0, 15), and the y-axis from 1 to 20 using ylim = c(1, 20). Again these commands are added within the plot function.
Next let’s add a title calling it “My Plot”. We’ll use the command main = “add your title here”.
Now, let’s spice up the colors of our plot. Let’s make the points red and bigger. We use the calls “col” and “cex” to adjust these items.
plot(x, y, col = "red", cex = 2, main = "My Plot", xlim = c(0, 15), ylim = c(1, 20), xlab = "Even", ylab = "Odd")
Now let’s make our points a little bit fancier. We can use the command pch to change the points from the standard hollow circle to a filled diamond (pch = 18). You can find a snapshot of the different pch symbols here. Since this is a filled symbol, the call col colors the outline and the call bg colors the fill of the symbol.
plot(x, y, pch = 23, bg = "yellow", col = "red", cex = 2, main = "My Plot", xlim = c(0, 15), ylim = c(1, 20), xlab = "Even", ylab = "Odd")
Finally let’s complete the plot by adding a legend. The legend is different than the previous calls. It goes outside of the plot() command. Add the legend() command on a second line. The first bit of code “topleft” adds the legend to the top left of the plot. The second bit of code calls the legend item by the name “my data”. The rest of the code defines the legend item as we added it into the plot. The exception is the call “pt.bg” which has to be used instead of just “bg”.
plot(x, y, pch = 23, bg = "yellow", col = "red", cex = 2, main = "My Plot", xlim = c(0, 15), ylim = c(1, 20), xlab = "Even", ylab = "Odd") legend("topleft", "my data", pch=22, pt.bg="yellow", col="red")
That’s it for now. We’ll do some more plotting next time!