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

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

问题描述

下面的代码可以很好地工作,并且可以正确地标记条形图,但是,如果我尝试使用 geom_text 进行直方图操作,我会失败,因为 geom_text 需要 y -分量和直方图的 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))  

我的问题:如何为获取正确的 y label (由表示?)> 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 需要 x y labels .但是, y labels 不在原始数据中,而是由 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天全站免登陆