R Histogram
Histograms
In the Bars chapter, you used barplot() to show one value for each category (A, B, C and D).
A histogram looks like a bar chart, but it shows how a set of numbers is spread out. R puts the numbers into ranges (called bins), and draws one bar for each range. The height of a bar shows how many numbers are in that range.
Use the hist() function to draw a histogram. Here, we use the test scores of 13 students:
Example
scores <- c(55, 62, 68, 70, 71, 75, 78, 80, 82, 85, 88, 91, 95)
hist(scores)
Result:
You can read the result like this: one student scored between 50 and 60, three students scored between 60 and 70, four scored between 70 and 80, and so on.
Note: There is no space between the bars, because the ranges follow each other: 50 to 60, 60 to 70, 70 to 80, and so on.
Title and Labels
Use the main parameter to add a title, and xlab and ylab to change the labels of the x-axis and y-axis:
Example
scores <- c(55, 62, 68, 70, 71, 75, 78, 80, 82, 85, 88, 91, 95)
hist(scores, main = "Test Scores", xlab = "Score", ylab = "Number of students")
Result:
Colors
Use the col parameter to change the color of the bars, and border to change the color of the lines around them:
Example
scores <- c(55, 62, 68, 70, 71, 75, 78, 80, 82, 85, 88, 91, 95)
hist(scores, col = "lightblue", border = "darkblue")
Result:
Choose the Bins
R chooses the bins for you. Use the breaks parameter to choose your own.
Here, we use the seq() function from the Vectors chapter to make bins of 5 points each, from 50 to 100:
Example
scores <- c(55, 62, 68, 70, 71, 75, 78, 80, 82, 85, 88, 91, 95)
hist(scores, breaks = seq(50, 100, by = 5))
Result:
Smaller bins show more details, but each bar has fewer values in it.