geom_text适用于R中的直方图?

时间:2016-08-04 23:17:57

标签: r ggplot2 histogram

想知道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()

enter image description here

的问候, 林

1 个答案:

答案 0 :(得分:3)

由于没人回答,我会试一试:

首先,提示一些:

  • 发布您的数据会让人们更有可能回答(因此我们无需复制)
  • 自己做一些研究还有很长的路要走。例如,你提到你想为每个条形标签 - 很好有几种方法可以做到这一点。快速谷歌搜索挖掘了这个:Customize axis labels

现在实际回答你的问题:

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)

enter image description here

关于..count..的问题,请参阅:Special variables in ggplot (..count.., ..density.., etc.)