Quartiles boxplot in R

Boxplots are one of the best ways to represent distributions. Below, there is some code to create a custom boxplot by determining the percentiles of the distribution that the whiskers and the box represent. In the example, I plotted the quartiles of the distribution of weight as a function of the group from the dataset PlantGrowth.

First, we create a function to extract quartiles. The values in probs represent the percentiles of the distributions, which then will be plotted. Then, we examine the quartiles of the distribution of weight for each group (i.e., ctrl, trt1, trt2).

# Create the function quartiles
quartiles <- function(x) {
  r <- quantile(x, probs=c(0, 0.25, 0.5, 0.75, 1))
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
  r
}

# Quartiles of weight per group
by(PlantGrowth$weight, INDICES = PlantGrowth$group, FUN = quartiles)
## PlantGrowth$group: ctrl
##   ymin  lower middle  upper   ymax 
## 4.1700 4.5500 5.1550 5.2925 6.1100 
## -------------------------------------------------------- 
## PlantGrowth$group: trt1
##   ymin  lower middle  upper   ymax 
## 3.5900 4.2075 4.5500 4.8700 6.0300 
## -------------------------------------------------------- 
## PlantGrowth$group: trt2
##   ymin  lower middle  upper   ymax 
## 4.9200 5.2675 5.4350 5.7350 6.3100

Finally, the boxplot using ggplot. I also added the diamond shape to represent the mean and the individual values jittered around the boxplot.

# Libraries
library(ggplot2)

# Plot
ggplot(data = PlantGrowth, aes(y=weight, x=group, width=0.3)) +
  stat_summary(fun.data = quartiles, geom="boxplot", size=0.7, fill="white") +
  stat_summary(fun.y = mean, geom = "point", shape=18, size=5) +
  geom_jitter(width = 0.1, height = 0, alpha=0.3, size=3) +
  theme_classic(base_size = 18) +
  guides(fill=guide_legend(title="Triplet")) +
  theme(axis.title.x = element_text(face="bold"),
        axis.title.y = element_text(face="bold"),
        legend.title = element_text(face="bold"),
        axis.text.x = element_text(colour = "Black"),
        axis.text.y = element_text(colour = "Black"),
        axis.ticks.x = element_line(colour = "Black", size = 0.2),
        axis.ticks.y = element_line(colour = "Black", size = 0.2),
        axis.line.x = element_line(size = 0.2),
        axis.line.y = element_line(size = 0.2),
        panel.border = element_rect(size = 0.2,color="black", fill=NA),
        plot.title = element_text(face="bold", hjust = 0.5),
        panel.grid.major = element_line(size = (0.1), colour="grey"),
        panel.grid.minor = element_blank()) +
  xlab("Group") +
  ylab("Weight") +
  ggtitle("Boxplot quartiles")


Comments

Popular posts from this blog

JASP - Statistical software

Cold shower

Get some morning light!