geom_text适用于R中的直方图吗? [英] geom_text works for histogram in R?
问题描述
想知道 geom_text
是否适用于 hist ?试过下面的代码,它似乎没有效果。当为每个柱状图桶绘制每个柱时,我只想显示标签(属于特定柱状图桶的元素数量)。任何解决方案,赞赏。谢谢。
p < - hist(df $ foo,
main =title,xlab =foo )
p + geom_text()
编辑1 ,尝试过 geom_bar
,这里是我的代码,它看起来不太好,因为我期望每个栏上都标有一个数字。在图中,它只显示2.5,5,7.5和10,我预计会显示1,2,3,...,9,10每个栏。
g < - ggplot(df,aes(df $ foo))
g + geom_bar()
问候,
Lin
由于没有人回答过这个问题,所以我会试一试:
首先,一些提示:
- 发布您的数据将使人们更有可能回答(因此我们不必复制它)
- 自己做一些研究会有很长的路要走。例如,你提到你想为每个酒吧添加一个标签 - 很好,有几种方法可以做到这一点。快速谷歌搜索挖掘这个:
至你关于
.. count的问题。 。
请参阅: ggplot中的特殊变量(..count ..,..density ..等)。Wondering if
geom_text
works forhist
? Tried following code and it seems no effect. I just want to show label (the number of elements belonging to a specific histogram bucket), when plotting each bar for each histogram bucket. Any solutions are appreciated. Thanks.p <- hist(df$foo, main="title",xlab="foo") p + geom_text()
Edit 1, tried
geom_bar
, here is my code and it seems not working well, since I expect a number labelled on each bar. In the diagram, it only shows 2.5, 5, 7.5 and 10, I expect to show 1, 2, 3, ..., 9, 10 for each bar.g <- ggplot(df, aes(df$foo)) g + geom_bar()
regards, Lin
解决方案Since no one has answered this I'll give it a try:
First, a few tips:
- posting your data will make it more likely for people to answer (so we don't have to replicate it)
- Doing some research on your own goes a long way. For example, you mention that you want a label for each bar - fine there are several ways to do it. A quick google search digs up this: Customize axis labels
Now to actually answer your question:
set.seed(1) #Make sample data since none is provided df <- data.frame(foo=sample(1:10,200,replace=T)) #This is what you want - use as.factor(foo) - this gives you the breaks at every bar. g <- ggplot(df, aes(as.factor(foo))) #Actually making the barplot and adding labels to it g + geom_bar() +stat_count(aes(y=..count..,label=..count..),geom="text",vjust=-1)
To your question about
..count..
see: Special variables in ggplot (..count.., ..density.., etc.).这篇关于geom_text适用于R中的直方图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 自己做一些研究会有很长的路要走。例如,你提到你想为每个酒吧添加一个标签 - 很好,有几种方法可以做到这一点。快速谷歌搜索挖掘这个: