【问题标题】:How to label a barplot bar with positive and negative bars with ggplot2如何使用ggplot2用正负条标记条形图
【发布时间】:2012-08-09 22:01:42
【问题描述】:

我正在尝试使用带有正负条的 ggplot2 绘制带标签的条形图。 到目前为止有效,但我想将标签设置在栏之外,使其位于栏的上方或下方。我尝试在vjust = c(x1,...,xn) 中设置调整,其中x 是根据geom_text() 中条形的值的正值或负值。这行不通。我刚刚收到错误消息错误:“设置美学时,它们可能只取一个值。问题:vjust”

使用正常的绘图命令。我想在 ggplot2 中复制这个命令:

xpos <- barplot(d, col=mycols, main='Verteilung in Dresden 2004',
         ylab='Anteil in %', xlab='Milieu', names.arg=l, 
         cex.axis=0.7, cex.names=0.7, ylim=c(0,max(d)+0.05))
boxed.labels(xpos,d+0.02,sprintf('%d%s', d*100, '%'),
          bg='transparent', border=FALSE, cex=0.7)

所以它看起来就像这样很好...... ;-)

有人有什么建议吗?

感谢大家的帮助。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这就是诀窍

    library(plyr)
    library(ggplot2)
    library(scales)
    dtf <- data.frame(x = c("ETB", "PMA", "PER", "KON", "TRA", 
                      "DDR", "BUM", "MAT", "HED", "EXP"),
                      y = c(.02, .11, -.01, -.03, -.03, .02, .1, -.01, -.02, 0.06))
    ggplot(dtf, aes(x, y)) +
      geom_bar(stat = "identity", aes(fill = x), legend = FALSE) + 
      geom_text(aes(label = paste(y * 100, "%"),
                   vjust = ifelse(y >= 0, 0, 1))) +
      scale_y_continuous("Anteil in Prozent", labels = percent_format()) +
      opts(axis.title.x = theme_blank())
    

    【讨论】:

    • 对于ifelse 中的值,我可能会使用-0.1 和1.1 而不是0 和1,但这只是为了将数字推离条形更远一点。这个概念是正确的。
    猜你喜欢
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多