获取值和位置以标记 ggplot 直方图 [英] Get values and positions to label a ggplot histogram

查看:17
本文介绍了获取值和位置以标记 ggplot 直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码运行良好,它正确标记了条形图,但是,如果我尝试 geom_text 获取直方图,我会失败,因为 geom_text 需要 y>-component 和直方图的 y 组件不是原始数据的一部分.

Below code works well and it labels the barplot correctly, However, if I try geom_text for a histogram I fail since geom_text requires a y-component and a histogram's y component is not part of the original data.

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

Label an "ordinary" bar plot (geom_bar(stat = "identity") works well:

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

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

My Problem: How to get the correct y and label (indicated by ?) for geom_text, to put labels on top of the histogram bars

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

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

geom_text requires x, y and labels. However, y and labels are not in the original data, but generated by the geom_histogram function. How can I extract the necessary data to position labels on a histogram?

推荐答案

geom_histogram() 只是对 stat_bin 的精美包装器,因此您可以自己使用条形图和你喜欢的文字.举个例子

geom_histogram() is just a fancy wrapper to stat_bin so you can all that yourself with the bars and text that you like. Here's an example

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

得到

这篇关于获取值和位置以标记 ggplot 直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆