Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding x coordinates of box in geom_boxplot (ggplot2)

Tags:

r

ggplot2

boxplot

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

like image 733
Mark Heckmann Avatar asked Dec 27 '25 23:12

Mark Heckmann


1 Answers

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)
like image 117
jeremycg Avatar answered Dec 30 '25 12:12

jeremycg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!