【问题标题】:Get values and positions to label a ggplot histogram获取值和位置以标记 ggplot 直方图
【发布时间】:2014-06-13 06:19:57
【问题描述】:

下面的代码运行良好,它正确标记了条形图,但是,如果我尝试使用geom_text 生成直方图,我会失败,因为geom_text 需要y-组件,而直方图的y 组件不是原始数据。

标记“普通”条形图 (geom_bar(stat = "identity") 效果很好:

 ggplot(csub, aes(x = Year, y = Anomaly10y, fill = pos)) +
        geom_bar(stat = "identity", position = "identity") +
        geom_text(aes(label = Anomaly10y,vjust=1.5))  

我的问题:如何为geom_text 获得正确的ylabel(由? 表示),以便将标签放在直方图条的顶部

ggplot(csub,aes(x = Anomaly10y)) + 
        geom_histogram() 
        geom_text(aes(label = ?, vjust = 1.5))

geom_text 需要 xylabels。但是ylabels不在原始数据中,而是由geom_histogram函数生成的。如何提取必要的数据以在直方图上定位标签?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    geom_histogram() 只是stat_bin 的精美包装,因此您可以使用自己喜欢的条形图和文本进行所有操作。这是一个例子

    #sample data
    set.seed(15)
    csub<-data.frame(Anomaly10y = rpois(50,5))
    

    然后我们用它来绘制它

    ggplot(csub,aes(x=Anomaly10y)) + 
        stat_bin(binwidth=1) + ylim(c(0, 12)) +  
        stat_bin(binwidth=1, geom="text", aes(label=..count..), vjust=-1.5) 
    

    得到

    【讨论】:

    • 附带说明,添加 + limits(x=c(0, 12)) 将显示 10 的标签。
    • @tonytonov 我应该这样做的。我继续更新示例以扩展范围,因此不会切断任何标签。
    • 谢谢,它的工作,但是,它抛出一个警告:“ymax 未定义:用 y 代替调整位置。”
    • 对于因子直方图,需要使用+ stat_count(binwidth=1, geom="text", aes(label=..count..), vjust=0.25),只要有人对这种情况有同样的问题......
    【解决方案2】:

    好的,让它在美学上有吸引力是解决方案:

    set.seed(15)
    csub <- data.frame(Anomaly10y = rpois(50, 5))
    

    现在画出来

    csub %>%
      ggplot(aes(Anomaly10y)) +
      geom_histogram(binwidth=1) +
      stat_bin(binwidth=1, geom='text', color='white', aes(label=..count..),
               position=position_stack(vjust = 0.5))
    

    结果情节将是

    【讨论】:

    • 可以用stat_bin()旋转标签吗?
    猜你喜欢
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 2016-05-20
    • 2019-09-23
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    相关资源
    最近更新 更多