如何在ggplot2中获得直方图的数据标签?

时间:2022-06-08 14:58:45

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 the frequency which is never a part of the code then HOW DO I bring labels for a Histogram?

下面的代码工作得很好,它正确地标记了条形图,但是,如果我尝试使用geom_text来表示我失败的直方图,因为geom_text需要一个y分量,而一个直方图的y分量是频率,这不是代码的一部分,那么我如何为直方图添加标签呢?

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

Problem- no Y component(indicated by ?) in the below code for geom_text

问题-在geom_text的下面代码中没有Y组件(由?表示)

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

By Default geom requires x and y component,

默认情况下,geom需要x和y分量,

What should I do when I dont have y-component as it is automatically generated by the function?

当我没有y分量时该怎么办,因为它是由函数自动生成的?

1 个解决方案

#1


32  

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

geom_histogram()只是stat_bin的一个漂亮的包装,因此您可以自己使用喜欢的条形和文本。这里有一个例子

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

And then we plot it with

然后画出来

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) 

to get

得到

如何在ggplot2中获得直方图的数据标签?

#1


32  

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

geom_histogram()只是stat_bin的一个漂亮的包装,因此您可以自己使用喜欢的条形和文本。这里有一个例子

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

And then we plot it with

然后画出来

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) 

to get

得到

如何在ggplot2中获得直方图的数据标签?