各个条上的数字对齐

时间:2012-04-11 19:26:42

标签: r ggplot2 bar-chart

我需要在ggplot上方的标签上方放置标签。我曾经使用找到的方法(HERE),但由于我的ggplot2更新,因为我现在收到错误消息,所以这似乎不再起作用了:

Error in continuous_scale(c("y", "ymin", "ymax", "yend", "yintercept",  : 
  unused argument(s) (formatter = "percent")

使用示例时,如何再次在条形图上方绘制数值:

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)

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

在win 7机器上运行R 2.15 ggplot2 0.9

1 个答案:

答案 0 :(得分:14)

错误来自scale_y_continuous来电。标签的格式化现在由labels参数处理。有关详细信息,请参阅ggplot2 0.9.0 transition guide

标签没有正确排列还有另一个问题;我通过在group=B的美学中添加geom_text来解决这个问题。不过,我不太清楚为什么这是必要的。我还从x=A美学中取出geom_text,因为它不需要(它会从ggplot调用继承。

library("ggplot2")
library("scales")

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, group=B),
              size = 3, position = position_dodge(width=0.9)) +
    scale_y_continuous(labels = percent) +
    theme_bw()

enter image description here