R Instructions: Histogram

To open R with the dataset preloaded, right-click here and choose "Save Target As" to download the file to your computer. Then find the downloaded file and double-click it to open it in R.

The data have been loaded into the data frame actor_age. Enter the command actor_age to see the data. The only variable (column title) in the data frame actor_age is Age.

To create a histogram of the actors' age data we can use the following code:

hist(actor_age$Age)

Notice the default settings in R are to use the variable name, in this case actor_age$Age in the title and x-axis label. In addition, the default y-axis is "Frequency." A good graphic is a well-labeled graphic. We can modify all of these settings with a few additional parameters added into the hist() command.

For example, if you want to add an x-axis label and remove the title of the histogram, use the following code:

hist(actor_age$Age, xlab="Age of Best Actor Oscar Winners (1970-2001)", main="")

If you want to modify the x-axis and y-axis label and the title use the following code:

hist(actor_age$Age, xlab="Age of Best Actor Oscar Winners (1970-2001)", ylab="Number of Actors", main="Best Actor Oscar Winners Ages")

Try replacing the x-axis label, y-axis label, and title with your own modified labels.

Another possible modification to the histogram is the number of bins. R uses an algorithm to determine the optimal number of bins based on the data, but in some cases you may want to modify the number of bins yourself. You can add the parameter breaks= into the hist() command which will tell R to make that many breaks in the data. R will not always do the exact number of breaks if it is not possible, but it will provide a close approximation. For example, let's try 8 breaks:

hist(actor_age$Age, breaks=8, xlab="Age of Best Actor Oscar Winners (1970-2001)", main="")

Try replacing the number of "breaks" with 5 or 20. Which histogram gives the right amount of detail - neither too little nor too much?

Note: Using R - If you are looking at a graph in R, you may find that the command window (the one labeled "R Console") is not responsive. That is because the graph window is the "active" window. Click on the command window to make it the active window. In addition, notice that R will always overwrite your current graphic with a new graphic. Enter the code x11() and press prior to each new graphic command and R will create a new window for that graphic.