Overview
This lesson introduces some basic visualization tools in R.
Objectives
After completing this lesson, students should be able to:
Readings
Lander, Chapter 7
Visualization is the best method for exploring and getting to know your data, as well as generating hypotheses and presenting results. R has robust graphics built in, and even better graphics through the ggplot2
package. We’ll start with the base graphics, and then look a bit more closely at ggplot2
.
In the previous module, we used aggregate
to examine mean temperatures by month in the airquality
dataset. We can get much richer information by visualizing these data.
To begin with, to display a single variable, we can generate a simple histogram using the base R function hist
:
hist(airquality$Temp,main="Temperature Histogram for Airquality",xlab="Temperature")
The first input is the data vector; “main” is the figure title; and “xlab” is the label for the x axis.
If we want a boxplot to summarize a single variable instead, we can use:
boxplot(airquality$Temp,main="Temperature Boxplot for Airquality",ylab="Temperature")
The boxplot displays the median (dark line), the middle two quartiles (ie, 25th-75th percentiles, or the interquartile range, IQR) in the box, and whiskers out to +/- 1.5 of the IQR.
Finally, if we want the simplest two-variable scatter plot, we can use plot
.
If we want to examine temperature as a function of date, we need to first construct a nice date variable, since right now the airquality data has dates by month number and day of the month. (Think about how paste is working here.)
airdate <- as.Date(paste("1972","-",airquality$Month,"-",airquality$Day,sep=""))
Now we can plot temperature as a function of day:
plot(airdate,airquality$Temp,xlab="Date",ylab="Temperature",main="Temperature by Day")
Rather than go more deeply into the base graphics of R, it is worth turning immediately to the more robust and beautiful ggplot2
graphics package, which is now fairly standard for R visualization.
The fundamental idea of ggplot is that you build up an image by adding together various functions. The core function is ggplot
, which takes your data plus a few settings and (silently) outputs it into a usable structure. The actual visualization is made by adding to ggplot
various other functions that take the structured data and output the actual graphics to your operating system.
As always, this is best illustrated with a few examples!
Here is our histogram from before in using ggplot2
:
library(ggplot2)
ggplot(data=airquality,aes(x=Temp)) + geom_histogram()
The first function ggplot
declares that the dataframe we are using is “airquality” and the x variable we want is “Temp” (“aes” stands for aesthetics, and can take many different aesthetic settings besides the variable names). geom_histogram
then takes that data and outputs the histogram; it too can take various settings in the “()” but we use only the default here.
To do a boxplot, we follow a similar syntax:
ggplot(data=airquality,aes(x=1,y=Temp)) + geom_boxplot()
The reason we need both an x and a y is that geom_boxplot
is by default designed to do boxplots over a number of groups. x=1
is just a way to get around this by making x a constant.
But if we wanted to boxplot temperature by month, we would write
ggplot(data=airquality,aes(x=as.factor(Month),y=Temp)) + geom_boxplot() + xlab("Month")
Note that we have to change the x variable to a factor so that ggplot knows how to group it. We also added another function to change the xlabel, which otherwise would be the ugly “as.factor(Month)”.
Finally, to do a scatter plot, you could probably almost guess the syntax by now, except for one thing. ggplot
likes to have its data all in a single dataframe, so first we have to add our “airdate” variable to the original dataframe:
airquality2 <- cbind(airquality,airdate)
ggplot(data=airquality2,aes(x=airdate,y=Temp)) + geom_point() + xlab("Date") + ylab("Temperature")
We can also add a line to this plot, which illustrates the power of ggplot
to build up images by adding layers:
ggplot(data=airquality2,aes(x=airdate,y=Temp)) + geom_point() + geom_line() + xlab("Date") + ylab("Temperature")
Finally, how do we save our plots?
This is easily done with ggplot2
using the ggsave
function, which can be executed after you have constructed your image. For instance, our current image is now the plot of temperature vs date with the connecting lines. To save that as a PDF (the best format to use for inclusion in a document), we write:
ggsave("tempvsdate.pdf",width=6,height=4)
To save the file as a png (a good format for the web), we just change the file name to “tempvsdate.png”.
Another alternative is to use RStudio to save graphics. This gives you a little more room to tinker with the size and format, although it is always best practice to include the save within your script for reproducibility.
To save the image in the “Plots” pane using RStudio, click on the “Export” tab right below the “Plots” tab in the “Plots” pane. To save as a PDF, for instance, choose “Save as PDF…”, which gives you the options to set the size and directory, and most importantly, to preview the results so you can get the size right. Different sizes even with the same width-to-height ratio produce different size text and other features, so it’s sometimes worth tinkering to get the most aethetically pleasing output.
We will see much more about graphics using the ggplot2
package as we progress. The key thing to bear in mind with ggplot
is that it is almost impossible to learn the syntax by heart, at least for all the little settings you will invariably want. So it is essential to have a good reference guide. The best guides are essentially little cookbooks, where you can either look up in the index by the ingredient you want, or look through the pictures for something that looks good.
In addition to our textbook, I especially recommend Cookbook for R, based on the excellent R Graphics Cookbook by Winston Chang. The online version makes it especially easy to find what you need with the minimum of hair-pulling. The utility of crib sheets and online references for R is always important, but it is especially essential for a visual medium like graphics, where often you may not know exactly what you need until you see it.