R Box Plot
Box Plots
A box plot shows how a set of numbers is spread out, in one small picture. It shows the middle value, where most of the values are, and values that are far away from the rest.
Use the boxplot() function to draw a box plot. Here, we use the same test scores as in the Histogram chapter:
Example
scores <- c(55, 62, 68, 70, 71, 75, 78, 80, 82, 85, 88, 91, 95)
boxplot(scores)
Result:
How to Read a Box Plot
- The thick line inside the box is the median: the middle value, when all the values are sorted. Half of the scores are below it, and half are above it.
- The box shows where the middle half of the values are.
- The lines above and below the box (called whiskers) go out to the lowest and the highest values that are not outliers.
- A value that is very far from the rest is drawn as a dot. It is called an outlier.
In this example, one student scored only 20. That score is far below the others, so it is drawn as a dot:
Example
scores <- c(20, 62, 68, 70, 71, 75, 78, 80, 82, 85, 88, 91, 95)
boxplot(scores)
Result:
Title, Label and Color
Use main to add a title, ylab to add a label, and col to change the color of the box:
Example
scores <- c(55, 62, 68, 70, 71, 75, 78, 80, 82, 85, 88, 91, 95)
boxplot(scores, main = "Test Scores", ylab = "Score", col = "lightblue")
Result:
Compare Groups
Box plots are very useful when you want to compare groups. Give boxplot() more than one vector, and use names to label each box:
Example
class_a <- c(55, 62, 68, 70, 71, 75, 78, 80, 82, 85, 88, 91, 95)
class_b <- c(48, 55, 60, 63, 65, 70, 72, 74, 79, 85)
boxplot(class_a, class_b, names = c("Class A", "Class B"))
Result:
Now it is easy to see that Class A has a higher median than Class B.
Horizontal Box Plot
Use horizontal = TRUE to draw the box plot from left to right:
Example
scores <- c(55, 62, 68, 70, 71, 75, 78, 80, 82, 85, 88, 91, 95)
boxplot(scores, horizontal = TRUE)
Result: