在qplot / ggplot中具有分数的直方图

时间:2011-10-17 07:51:11

标签: r ggplot2

enter image description here到目前为止,我已经错过了y轴上有一个分数的直方图函数。像这样:

require(ggplot2)
data(diamonds)
idealD <- diamonds[diamonds[,"cut"]=="Ideal",]

fracHist <- function(x){
  frac <- (hist(x,plot=F)$counts) / (sum(hist(x,plot=F)$counts))
  barplot(frac)
}

### call
fracHist(idealD$carat)

它不漂亮,但基本上应该解释我想要的东西:酒吧高度应该加起来一个。此外,断裂应标记x轴。我希望通过ggplot2 but can't figure out how to get around plotting the frequencies of frac instead of plotting frac itself创建相同内容。

all I get with `ggplot` is density...

m <- ggplot(idealD, aes(x=carat)) 
m + geom_histogram(aes(y = ..density..)) + geom_density()

2 个答案:

答案 0 :(得分:8)

解决方案是使用stat_bin并映射审美y=..count../sum(..count..)

library(ggplot2)
ggplot(idealD, aes(x=carat)) + stat_bin(aes(y=..count../sum(..count..)))

快速扫描?hist我无法找到hist中值的分区方式。这意味着除非您使用binwidth的{​​{1}}参数,否则图表将不相同。

enter image description here

答案 1 :(得分:0)

这个技巧也适用于geom_histogram直方图。

require(ggplot2)
data(diamonds)
idealD <- diamonds[diamonds[,"cut"]=="Ideal",]

ggplot(idealD, aes(x=carat))  +   geom_histogram(aes(y=..count../sum(..count..)))

enter image description here