Skip to Main Content
Graphing Data with R
book

Graphing Data with R

by John Jay Hilfiger
October 2015
Beginner to intermediate content levelBeginner to intermediate
250 pages
6h 26m
English
O'Reilly Media, Inc.
Content preview from Graphing Data with R

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

A Course in Statistics with R

A Course in Statistics with R

Prabhanjan N. Tattar, Suresh Ramaiah, B. G. Manjunath

Publisher Resources

ISBN: 9781491922606Errata Page