3
votes

I want to add text to indicate the median and hinges in a boxplot (left or right of the box). I am struggling with the horizontal positioning of the text. How can I calculate the x coordinates of the box (left and right)? (or how can I position them adequately to the left or right of the box).

set.seed(0)
d <- data.frame(x = rnorm(20))
pos <- quantile(d$x)[2:4]
s <- data.frame(pos, q=names(pos))

ggplot(d, aes("A", x)) + 
  geom_boxplot() +
  geom_text(aes(y=pos, label=q), s, hjust=5)

enter image description here

1

1 Answers

3
votes

For a box plot, ggplot2 makes the first boxplot at x=1, then the next at x=2, 3, 3 etc. If you only have one plot at each factor level (ie haven't subdivided at these points), the width of the bar is 0.75, with 0.375 on each side.

So, for your example, you want to add the geom_text with x = (1 - 0.375) with a little room to make sure it doesn't overlap:

library(ggplot2)

set.seed(0)
d <- data.frame(x = rnorm(20))
pos <- quantile(d$x)[2:4]
s <- data.frame(pos, q=names(pos))

ggplot(d, aes("A", x)) + 
  geom_boxplot() +
  geom_text(aes(y=pos, label=q), x=1-0.375,s)

enter image description here

If you have more than one boxplot, you want to make the call:

geom_text(aes(y=pos, label=q, x = as.numeric(factor(var))-0.375), s)