2017-02-16 72 views
0

如何使用geom_text()将“number”字段添加到每个上方错误栏旁边。即在上部错误栏的右侧。使用geom_text在错误栏旁边添加文本

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))) 

回答

2
  • aes(label = number, x = as.numeric(u))使用数字作为标签和上部误差棒的X坐标。 y坐标将保持与您在ggplot中指定的相同。
  • hjust = -1将对齐文本标签并将其右移。
  • 使用xlim()来调整可能超出右边缘的文字。

实施例:

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