user3022875
user3022875

Reputation: 9018

adding text next to error bar using geom_text

How can I use geom_text() to add the "number" field next to each upper error bar. i.e. to the right of the upper error bar.

 group= 1:10
count = c(41,640,1000,65,30,4010,222,277,1853,800 )
mu = c(.7143,.66,.6441,.58,.7488,.5616,.5507,.5337,.5513,.5118)
sd = c(.2443,.20,.2843,.2285,.2616,.2365,.2408,.2101,.2295,.1966)
u = mu + 1.96*sd/sqrt(count)
l=  mu - 1.96*sd/sqrt(count)
number = c(23,12,35,32,23,63,65,66,66,66)
dat = data.frame(group= group, count = count, mu = mu, sd = sd,u,u,l=l,number = number)
dat[order(dat$count),]



ggplot(dat,  aes(y=factor(group), x=  mu)) +
  geom_point()+
  geom_errorbarh(aes(xmax = as.numeric(u),xmin = as.numeric(l)))

Upvotes: 1

Views: 1919

Answers (1)

Simon Jackson
Simon Jackson

Reputation: 3174

  • aes(label = number, x = as.numeric(u)) to use numbers as the labels and the upper error bar the x coordinates. The y coordinates will remain the same as you've specified in ggplot.
  • hjust = -1 will justify text labels and shift them right.
  • Use xlim() to adjust for text that might go over the right edge.

Example:

ggplot(dat,  aes(y=factor(group), x=  mu)) +
  geom_point()+
  geom_errorbarh(aes(xmax = as.numeric(u),xmin = as.numeric(l))) +
  geom_text(aes(label = number, x = as.numeric(u)), hjust = -1) +
  xlim(.49, .85)

enter image description here

Upvotes: 3

Related Questions