2019-09-13

How to annotate a boxplot in ggplot2

Problem

We want to annotate a boxplot in ggplot2. In our example we will add Tukey's five number summary (minimum, lower-hinge, median, upper-hinge, and maximum).

fivenum(iris$Sepal.Width)
[1] 2.0 2.8 3.0 3.3 4.4
library(ggplot2)
ggplot(iris, aes(factor(0), Sepal.Width)) + 
geom_boxplot() + xlab("") + scale_x_discrete(breaks = NULL)

Solution

We store Tukey's five number summary as a data frame, and then pass it as the argument data inside geom_text to add text to the plot.

five <- data.frame(x = rep(1, 5), five = fivenum(iris$Sepal.Width))
ggplot(iris, aes(x = 0, y = Sepal.Width)) + 
  geom_boxplot() + xlab("") + scale_x_discrete(breaks = NULL) + 
  geom_text(data = five, aes(x = 0, y = five, label = five), nudge_x = 0.5)

References

No hay comentarios:

Publicar un comentario

Nube de datos