2015-05-04 45 views
1

我想要一个很好的密度(即总和为1)一些离散数据的直方图。我尝试了几种方法来做到这一点,但没有一个是完全令人满意的。ggplot2密度直方图与宽度= .5,vline和居中酒吧位置

产生一些数据:

#data 
set.seed(-999) 
d.test = data.frame(score = round(rnorm(100,1))) 
mean.score = mean(d.test[,1]) 
d1 = as.data.frame(prop.table(table(d.test))) 

首先给出了条正确的位置 - 中心数量的顶部 - 但vline()错了位置。这是因为x轴是离散的(因子),所以平均值使用的是层数而不是值。平均值是.89。

ggplot(data=d1, aes(x=d.test, y=Freq)) + 
    geom_bar(stat="identity", width=.5) + 
    geom_vline(xintercept=mean.score, color="blue", linetype="dashed") 

enter image description here

第二给出正确vline()放置(因为x轴是连续的),但是,当x轴是连续的杆错误放置和width参数不出现可修改(see here)。我也尝试了size参数,这也没有效果。同上hjust

ggplot(d.test, aes(x=score)) + 
    geom_histogram(aes(y=..count../sum(..count..)), width=.5) + 
    geom_vline(xintercept=mean.score, color="blue", linetype="dashed") 

enter image description here

任何想法?我的坏主意是重新调整平均值,以便它与因子水平相符并使用第一种解决方案。如果某些因素级别“缺失”,这将无法正常工作,例如1,2,4,没有因子3,因为没有数据点有这个值。如果平均值为3.5,则重新调整此值为奇数(x轴不再是interval scale)。

另一个想法是这样的:

ggplot(d.test, aes(x=score)) + 
    stat_bin(binwidth=.5, aes(y= ..density../sum(..density..)), hjust=-.5) + 
    scale_x_continuous(breaks = -2:5) + #add ticks back 
    geom_vline(xintercept=mean.score, color="blue", linetype="dashed") 

但是这需要调整休息,而酒吧仍然在错误的位置(不居中)。不幸的是,hjust似乎不起作用。

enter image description here

我如何获得我想要的一切?

  • 密度总和为1
  • 条以上为中心在正确的数
  • 宽度值
  • vline() = 0.5

随着碱的图形,一个或许可以通过绘制解决这个问题两次在x轴上。这里有类似的方法吗?

回答

3

这听起来像你只是想确保你的x轴的值是数值,而不是因素

ggplot(data=d1, aes(x=as.numeric(as.character(d.test)), y=Freq)) + 
    geom_bar(stat="identity", width=.5) + 
    geom_vline(xintercept=mean.score, color="blue", linetype="dashed") + 
    scale_x_continuous(breaks=-2:3) 

这给

enter image description here

+0

傻,我没有检查'数据.frame'来查看'prop.table()'给出了哪种类型。它输出“字符”和“数据”。因为'stringsAsFactors = F'没有被设置,所以frame()'因此将它转换为'factor'。 – Deleet

+1

@Deleet这个(各种)的反向选项将是在因子水平的加权平均值上绘制垂直线:'with(d1,weighted.mean(as.integer(d.test),w = Freq) )'。 – joran

+0

@Joran可能有效,但如果某些级别不存在,则会产生奇怪的结果(例如,由于小数据集中的抽样错误)。 – Deleet