Reorder Boxplots in R with Examples

Reorder Boxplots in R, you may need to reorder boxplots frequently.

The examples below demonstrate how to accomplish it using two distinct methods.

Method 1: Reorder based on a predetermined sequence

The built-in airquality dataset in R will be used in each example.

Principal Component Analysis in R

Take a look at the first six lines of air quality data

head(airquality)
  Ozone Solar.R Wind Temp Month Day
1    41     190  7.4   67     5   1
2    36     118  8.0   72     5   2
3    12     149 12.6   74     5   3
4    18     313 11.5   62     5   4
5    NA      NA 14.3   56     5   5
6    28      NA 14.9   66     5   6

Without setting an order, here’s what a plot of many boxplots for this dataset will look like.

generate a boxplot that depicts the temperature distribution by month.

boxplot(Temp~Month, data=airquality, col=rainbow(unique(airquality$Month)), border="black")

Example 1: Boxplots should be reordered based on a specific order

The following code demonstrates how to order the boxplots based on the Month variable’s order: 5, 8, 6, 9, 7.

airquality$Month <- factor(airquality$Month , levels=c(5, 8, 6, 9, 7))

create a boxplot of temperatures by month using the order we specified

tidyverse in r – Complete Tutorial » Unknown Techniques »

boxplot(Temp~Month, data=airquality, col= rainbow(unique(airquality$Month)),border="black")

The boxplots are now displayed in the order we selected with the levels argument.

Method 2: Reorder based on the Boxplot’s Median Value

The following code demonstrates how to order the boxplots in ascending order based on each month’s median temperature value.

Example 2: Using the Median Value to Reorder Boxplots

reorder Month values are listed in ascending order based on the Temp median value.

airquality$Month <- with(airquality, reorder(Month , Temp, median , na.rm=T))

make a month-by-month temperature boxplot

boxplot(Temp~Month, data=airquality, col="pink", border="black")

The boxplots are now arranged in ascending order by the month’s median value.

The horizontal black line that passes through the center of each boxplot represents the median value for that box.

We can also use a negative sign in front of Temp in the reorder function to order the boxplots in descending order.

based on the median value of Temp, reorder Month values in descending order

airquality$Month <- with(airquality, reorder(Month , -Temp, median , na.rm=T))

make a month-by-month temperature boxplot

boxplot(Temp~Month, data=airquality, col="yellow", border="black")

The boxplots now appear in descending order based on the median value for each month.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

four × 5 =

finnstats