boxplot(mtcars$mpg)
In this chapter, we will learn to
The box plot is a standardized way of displaying the distribution of data based on the five number summary: minimum, first quartile, median, third quartile, and maximum. Box plots are useful for detecting outliers and for comparing distributions. It shows the shape, central tendency and variability of the data.
A boxplot splits the data set into quartiles. The body of the boxplot consists of a “box” (hence, the name), which goes from the first quartile (Q1) to the third quartile (Q3). Within the box, a vertical line is drawn at the Q2, the median of the data set. Two horizontal lines, called whiskers, extend from the front and back of the box. The front whisker goes from Q1 to the smallest non-outlier in the data set, and the back whisker goes from Q3 to the largest non-outlier. If the data set includes one or more outliers, they are plotted separately as points on the chart.
Let us begin by creating a basic box plot. We will use the boxplot() function and specify the data.
Use the horizontal argument in the boxplot() function to create a horizontal box plot.
Let us add some color to the boxplot. Use the col argument to specify a color for the plot.
We can specify a separate color for the border of the box in the boxplot. To modify the border color, use the border argument.
The range argument determines how far the plot whiskers extend out from the box. If range is positive, the whiskers extend to the most extreme data point which is no more than range times the interquartile range from the box. A value of zero causes the whiskers to extend to the data extremes.
Let us set the value of range to 0 and observe the plot.
In the below plot, we set the value of range to 1.
Let us observe how the plot appears as we change the value of range from 0 to 1.

The outliers in the plot are not drawn if the outline argument is set to FALSE. The default value is TRUE.
The below plot displays how the plot changes with the values set for outline:

If the varwidth argument is set to TRUE, the boxes are drawn with widths proportional to the square-roots of the number of observations in the groups.
As we said in the introduction, box plots can be used to compare distributions of several variables. Let us use the mtcars data set and compare the distribution of Miles Per Gallon (mpg) for automobiles with different number of cylinders (cyl). We will do this by specifying a formula as shown in the below example.
We use the formula when we are comparing the distribution of a continuous variable across different levels of a categorical variable. If we want to compare the distributions without using a categorical variable, we need to specify the variable separately in the boxplot() function. Below is an illustration of this method. We will split the mpg data using the split() function and plot them separately. The split() function splits a continuous variable based on the levels of a categorical variable.
mpg_split <- split(mtcars$mpg, mtcars$cyl)
mpg_split
## $`4`
## [1] 22.8 24.4 22.8 32.4 30.4 33.9 21.5 27.3 26.0 30.4 21.4
##
## $`6`
## [1] 21.0 21.0 21.4 18.1 19.2 17.8 19.7
##
## $`8`
## [1] 18.7 14.3 16.4 17.3 15.2 10.4 10.4 14.7 15.5 15.2 13.3 19.2 15.8 15.0
mpg_4 <- mpg_split$`4`
mpg_6 <- mpg_split$`6`
mpg_8 <- mpg_split$`8`
boxplot(mpg_4, mpg_6, mpg_8)
The same plot can be created in two ways. If you are comparing the distribution of a continuous variable for the different levels of a categorical variable, use the formula. If you are comparing distribution of independent variables, specify all the variables in the boxplot() function.
Let us add some color to the plot. We can specify as many colors as the boxes or we can specify the same color for all of them. Below are two examples where we specify the same color in the first one and different colors in the second one.
If we want to test whether the medians of the different groups differ, we can use the notch argument and set it to TRUE. A notch is drawn in each side of the boxes and if the notches of the plots do not overlap, it is strong evidence that the medians differ.
We will use a different data set for this example. We use the hsb2 data (High School and Beyond survey, 200 observations; vendored as data/hsb2.csv, originally from the UCLA Institute for Digital Research and Education) and compare the distribution of reading score (read) for males and females (female).
hsb <- read.csv('data/hsb2.csv')
boxplot(hsb$read ~ hsb$female, notch = TRUE,
col = c('red', 'blue'))
Since the notches overlap, there is no strong evidence that the medians differ.
Let us conclude by adding a title and axis labels to the box plot.
---
description: "Base R box plots: the five-number summary, grouped boxplots from a formula, and notch for comparing medians, using the High School and Beyond survey data."
---
# Box Plots {#box}
## Introduction
In this chapter, we will learn to
- create univariate/multivariate box plots
- interpret box plots
- create horizontal box plots
- detect outliers
- modify box color
- use formula to compare distributions of different variables
- use notches to compare medians
## Box Plot
The box plot is a standardized way of displaying the distribution of data based on the five number summary: minimum, first quartile, median, third quartile, and maximum. Box plots are useful for detecting outliers and for comparing distributions. It shows the shape, central tendency and variability of the data.
### Structure
A boxplot splits the data set into quartiles. The body of the boxplot consists of a "box" (hence, the name), which goes from the first quartile (Q1) to the third quartile (Q3). Within the box, a vertical line is drawn at the Q2, the median of the data set. Two horizontal lines, called whiskers, extend from the front and back of the box. The front whisker goes from Q1 to the smallest non-outlier in the data set, and the back whisker goes from Q3 to the largest non-outlier. If the data set includes one or more outliers, they are plotted separately as points on the chart.
## Univariate Box Plot
### Basic Plot
Let us begin by creating a basic box plot. We will use the `boxplot()` function and specify the data.
```{r box1, fig.align='center', fig.width=5, fig.height=5}
boxplot(mtcars$mpg)
```
### Horizontal Box Plot
Use the `horizontal` argument in the `boxplot()` function to create a horizontal box plot.
```{r box2, fig.align='center', fig.width=5, fig.height=5}
boxplot(mtcars$mpg, horizontal = TRUE)
```
### Color
Let us add some color to the boxplot. Use the `col` argument to specify a color for the plot.
```{r box3, fig.align='center', fig.width=5, fig.height=5}
boxplot(mtcars$mpg, col = 'blue')
```
### Border Color
We can specify a separate color for the border of the box in the boxplot. To modify the border color, use the `border` argument.
```{r box4, fig.align='center', fig.width=5, fig.height=5}
boxplot(mtcars$mpg, border = 'red')
```
### Range
The `range` argument determines how far the plot whiskers extend out from the box. If range is positive, the whiskers extend to the most extreme data point which is no more than range times the interquartile range from the box. A value of zero causes the whiskers to extend to the data extremes.
Let us set the value of `range` to 0 and observe the plot.
```{r box5, fig.align='center', fig.width=5, fig.height=5}
boxplot(mtcars$mpg, range = 0)
```
In the below plot, we set the value of `range` to 1.
```{r box6, fig.align='center', fig.width=5, fig.height=5}
boxplot(mtcars$mpg, range = 1)
```
Let us observe how the plot appears as we change the value of `range` from 0 to 1.
```{r box7, fig.align='center', fig.width=10, fig.height=10, echo=FALSE}
init <- par(no.readonly = TRUE)
par(mfrow = c(2, 2))
values <- c(0, 0.25, 0.63, 1)
for (i in values) {
boxplot(mtcars$mpg, range = i)
mtext(paste("range = ", i), side = 3, col = "blue")
}
par(init)
```
### Outline
The outliers in the plot are not drawn if the `outline` argument is set to `FALSE`. The default value is `TRUE`.
```{r box8, fig.align='center', fig.width=5, fig.height=5}
boxplot(mtcars$mpg, range = 1, outline = FALSE)
```
The below plot displays how the plot changes with the values set for `outline`:
```{r box9, fig.align='center', fig.width=10, fig.height=5, echo=FALSE}
init <- par(no.readonly = TRUE)
par(mfrow = c(1, 2))
values <- c(TRUE, FALSE)
for (i in values) {
boxplot(mtcars$mpg, outline = i, range = 1)
mtext(paste("outline = ", i), side = 3, col = "blue")
}
par(init)
```
### Varwidth
If the `varwidth` argument is set to `TRUE`, the boxes are drawn with widths proportional to the square-roots of the number of observations in the groups.
```{r, fig.align='center', fig.width=10, fig.height=5, echo=FALSE}
#| label: fig-box-summary
#| fig-cap: "The five-number summary drawn on the same scale as the box plot"
#| fig-alt: "A horizontal strip showing a box plot of a grouped variable alongside text marking the minimum, lower hinge, median, upper hinge and maximum, positioned so each statistic lines up with the corresponding feature of the box."
init <- par(no.readonly = TRUE)
par(mfrow = c(1, 2))
values <- c(TRUE, FALSE)
for (i in values) {
boxplot(mtcars$mpg, varwidth = i, range = 1)
mtext(paste("varwidth = ", i), side = 3, col = "blue")
}
par(init)
```
## Bivariate/Multivariate Box Plot
As we said in the introduction, box plots can be used to compare distributions of several variables. Let us use the `mtcars` data set and compare the distribution of Miles Per Gallon (`mpg`) for automobiles with different number of cylinders (`cyl`). We will do this by specifying a formula as shown in the below example.
```{r box11, fig.align='center', fig.width=5, fig.height=5}
boxplot(mtcars$mpg ~ mtcars$cyl)
```
We use the formula when we are comparing the distribution of a continuous variable across different levels of a categorical variable. If we want to compare the distributions without using a categorical variable, we need to specify the variable separately in the `boxplot()` function. Below is an illustration of this method. We will split the `mpg` data using the `split()` function and plot them separately. The `split()` function splits a continuous variable based on the levels of a categorical variable.
```{r box12, fig.align='center', fig.width=5, fig.height=5, collapse=TRUE}
mpg_split <- split(mtcars$mpg, mtcars$cyl)
mpg_split
mpg_4 <- mpg_split$`4`
mpg_6 <- mpg_split$`6`
mpg_8 <- mpg_split$`8`
boxplot(mpg_4, mpg_6, mpg_8)
```
The same plot can be created in two ways. If you are comparing the distribution of a continuous variable for the different levels of a categorical variable, use the formula. If you are comparing distribution of independent variables, specify all the variables in the `boxplot()` function.
### Color
Let us add some color to the plot. We can specify as many colors as the boxes or we can specify the same color for all of them. Below are two examples where we specify the same color in the first one and different colors in the second one.
#### Single Color
```{r box14, fig.align='center', fig.width=5, fig.height=5}
boxplot(mtcars$mpg ~ mtcars$cyl, col = 'blue')
```
#### Different Colors
```{r box15, fig.align='center', fig.width=5, fig.height=5}
boxplot(mtcars$mpg ~ mtcars$cyl,
col = c('red', 'blue', 'yellow'))
```
### Compare Medians
If we want to test whether the medians of the different groups differ, we can use the `notch` argument and set it to `TRUE`. A notch is drawn in each side of the boxes and if the notches of the plots do not overlap, it is strong evidence that the medians differ.
We will use a different data set for this example. We use the `hsb2` data (High School and Beyond survey, 200 observations; vendored as `data/hsb2.csv`, originally from the UCLA Institute for Digital Research and Education) and compare the distribution of reading score (`read`) for males and females (`female`).
```{r box16, fig.align='center', fig.width=5, fig.height=5}
hsb <- read.csv('data/hsb2.csv')
boxplot(hsb$read ~ hsb$female, notch = TRUE,
col = c('red', 'blue'))
```
Since the notches overlap, there is no strong evidence that the medians differ.
## Putting it all together
Let us conclude by adding a title and axis labels to the box plot.
```{r box17, fig.align='center', fig.width=5, fig.height=5}
boxplot(mtcars$mpg ~ mtcars$cyl, range = 1, outline = TRUE,
horizontal = TRUE, col = c('red', 'blue', 'yellow'),
main = 'Miles Per Gallon by Cylinders',
ylab = 'Number of Cylinders', xlab = 'Miles Per Gallon',
names = c('Four', 'Six', 'Eight'))
```