获取ggplot2条形图中分组条的中点值

时间:2012-05-31 02:04:34

标签: r ggplot2

此代码

library(ggplot2)  

test=read.table(text= 
"group fillcd percent
1 1 73.2
1 2 73.8
1 3 78.6
2 1 78.1
2 2 95.6
2 3 95.5
", header=TRUE, sep=""  )        

test$fill <- factor(test$fillcd, labels=c("XX", "EE", "BB"))
test$text=paste(test$percent,"%")

ggplot(data=test, 
  aes(group, percent, fill=fill)) + 
    geom_bar(stat="identity",position="dodge")+
    coord_flip()+  
    geom_text(data = test, aes(y = percent, x = group, label = text ))

生成以下图表: enter image description here

如何获得条形的中点以在其中放置标签?

1 个答案:

答案 0 :(得分:6)

我不确定你的意思是水平还是垂直中点,但下面的例子可能会有所帮助:

ggplot(data=test, 
       aes(group, percent, fill=fill)) + 
         geom_bar(stat="identity",position=position_dodge(width = 0.9))+
         coord_flip()+  
         geom_text(data = test, aes(y = percent/2, x = group, label = text ), 
           position = position_dodge(width = 0.9))

enter image description here

关键是position_dodge