dww
dww

Reputation: 31452

vertically align asterisks (stars) in ggplot

In ggplot, I want to label some error bars with asterisks ('*') to indicate significance level. The graph is arranged with category labels on the y axis, so that they are easily legible. This means that the error bars are horizontal, and the *'s need to align vertically with them. However, the symbol '*' is not vertically centred in a line of text, so it gets plotted too high using geom_text.

Reproducible example

set.seed(123)
x = data.frame(grp = LETTERS[1:8], val = sample(10,8))
se = runif(8, 0.1,2)
x$upper = x$val + se
x$lower = x$val - se
x$labs = sample(c('*','**', '***', ''), 8, T)

gg = ggplot(x, aes(grp,val)) +
  geom_point() +
  geom_errorbar(aes(ymax = upper, ymin=lower), width=0.3) +
  scale_y_continuous(limits = c(-2,12)) +
  coord_flip()

gg + geom_text(aes(y=upper+0.2, label=labs), size=8, hjust='left')

enter image description here

I know that I can nudge the label position like this:

gg + geom_text(aes(y=upper+0.2, label=labs), size=8, nudge_x = -0.2, hjust='left')

However, getting the correct value of nudge_x needs to be done in an ad-hoc manner and the correct value varies with size of graphics output, font size, number of categories on the y scale etc. Is there a way to get the labels to automatically align vertically? I tried using geom_point with shape=42 instead of geom_text to draw the asterisks. Although this solves the vertical alignment issue, it introduces its own problem with getting the spacing between a horizontal row of asterisks correct (i.e. getting '**' and '***' to print with the correct separation between adjacent symbols).

Upvotes: 3

Views: 2026

Answers (1)

joran
joran

Reputation: 173627

Just eyeballing it on my machine, it looks like this vjust adjustment seems to work, and I think it may be fairly robust to changes in device output size, font size, etc.

gg + geom_text(aes(y=upper+0.2, label=labs), size=8, hjust='left',vjust = 0.77)

Upvotes: 2

Related Questions