Chapter 9. Bar Plots (Bar Charts)

Basic Bar Plot

Let’s revisit the Salaries dataset from Chapter 7. In Figure 7-5, we  produced a display of six histograms, showing the distribution of faculty salaries in each of six combinations of rank and gender. Another interesting way of looking at the data would be to compare the counts of faculty members in each defined group. Let’s begin with a simpler graph, representing just counts of the three faculty ranks. If we knew the counts in each rank, we could type them into a vector, such as in the following:

> ranknum = c(67,64,266)

then make a bar plot (also called a “bar chart”) from the ranknum vector:

> barplot(ranknum)

If the counts are unknown, we can use the table() function to put these counts into a vector, and then have barplot() operate on that vector:

# preliminary to Fig. 9-1
install.packages("car")   # if you have not yet installed car
library(car)
attach(Salaries)
rankcount = table(rank) #get counts & save in vector rankcount
rankcount           # print results

rank
 AsstProf AssocProf      Prof
       67        64       266

The barplot() function shown in the code that follows uses bar height to represent the elements in a vector; in this case, it is the counts of each faculty rank. Thus, the graph will have three bars, the first two of nearly equal height, and the third one about four times the height of the other two:

# Fig. 9-1a
barplot(rankcount, ylab = "Count", col = "skyblue",
  main = "Faculty by Rank", sub = "a. Number in each rank")

Figure 9-1a shows ...

Get Graphing Data with R now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.