【问题标题】:geom_bar with annotation inside bars aligned with x-axis带有注释的 geom_bar 与 x 轴对齐的条内
【发布时间】:2014-07-15 08:58:56
【问题描述】:

我正在尝试使用 geom_bar 创建结果的直方图,并希望将结果计数作为文本包含在与 x 轴对齐的每个条形中。

这是我目前所拥有的:

df <- data.frame(results = rnorm(100000))

require(ggplot2)

p = ggplot(df, aes(x =  results)) 

p = p + geom_bar(binwidth = 0.5, colour = "black", fill = "white", drop = T)

p = p + scale_y_log10()

p = p + geom_hline(aes(yintercept = 1))

p = p + stat_bin(geom = "text", binwidth = 0.5,
             aes(x = results, angle = 90, y = 2, 
                 label = gsub(" ", "",format(..count.., big.mark = ",", 
                                             scientific=F)))) 

p

如您所见,文本未与 x 轴对齐,并且由于我的真实数据要大得多(以百万计),这个问题会变得更糟:

当前图:

想要的图:

注意:通过在 stat_bin 中设置 y = 3,我会收到一条警告,指出“将变量映射到 y 并使用 stat="bin".etc...”,但我不确定如何强制文本的位置位于图表底部而不定义 y 值。

【问题讨论】:

  • 附注:当我运行您的代码时,我收到一个错误(不是警告):“Error : Mapping a variable to y and also using stat="bin”。 ggplot2_1.0.0

标签: r ggplot2


【解决方案1】:

您可以通过交换geomstat 来做到这一点。换句话说,使用geom_text(stat="bin", ...)

这允许您显式设置y 位置(即在aes 之外)并指定与hjust=0 的文本对齐方式。

试试这个:

ggplot(df, aes(x =  results)) +
  geom_bar(binwidth = 0.5, colour = "black", fill = "white", drop = T) +
  scale_y_log10() +
  geom_hline(aes(yintercept = 1)) +
  geom_text(stat="bin", binwidth = 0.5, y=0.1, hjust=0,
           aes(x = results, angle = 90, 
               label = gsub(" ", "", format(..count.., big.mark = ",", 
                                            scientific=F)))) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-20
    • 2014-08-28
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多