2017-02-16 73 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