2012-02-07 28 views
5

我想在下图中的单条上显示数字。使用ggplot2对齐单条上的数字

df <- structure(list(A = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 
3L), .Label = c("0-50,000", "50,001-250,000", "250,001-Over"), class = "factor"), 
    B = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("0-50,000", 
    "50,001-250,000", "250,001-Over"), class = "factor"), Freq = c(0.507713884992987, 
    0.258064516129032, 0.23422159887798, 0.168539325842697, 0.525280898876405, 
    0.306179775280899, 0.160958904109589, 0.243150684931507, 
    0.595890410958904)), .Names = c("A", "B", "Freq"), class = "data.frame", row.names = c(NA, 
-9L)) 

library(ggplot2) 
p <- ggplot(data=df, aes(x=A, y=Freq))+ 
      geom_bar(aes(fill=B), position=position_dodge()) + theme_bw() 
p <- p + scale_y_continuous(formatter="percent") 
p <- p + geom_text(aes(label = paste(sprintf("%.1f", Freq*100), "%", sep=""), y = Freq+0.015, x=A), size = 3) 
print(p) 

enter image description here

我无法弄清楚如何把数字沿x轴的位置上。任何帮助将非常感激。谢谢

回答

8

您需要将position=position_dodge(width=0.9)添加到geom_text调用。

清理代码有点给出:

p <- ggplot(data=df, aes(x=A, y=Freq))+ 
    geom_bar(aes(fill=B), position = position_dodge()) + 
    geom_text(aes(label = paste(sprintf("%.1f", Freq*100), "%", sep=""), 
        y = Freq+0.015, x=A), 
       size = 3, position = position_dodge(width=0.9)) + 
    scale_y_continuous(formatter = "percent") + 
    theme_bw() 

导致

enter image description here

+0

(+1):谢谢布赖恩为有用的答案。 – MYaseen208 2012-02-07 22:50:37

+1

@ MYaseen208感谢包括数据在内的完全可重复的问题。回答(好吧,检查我的回答是否正确)要容易得多。 – 2012-02-07 22:52:48

+1

更新为ggplot2 0.9.0的这个答案在http://stackoverflow.com/a/10113480/892313 – 2012-04-11 20:32:34