【发布时间】:2015-05-04 21:31:32
【问题描述】:
我想要一些离散数据的良好密度(总和为 1)直方图。我已经尝试了几种方法来做到这一点,但没有一个是完全令人满意的。
生成一些数据:
#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 轴是离散的(因子),因此平均值是使用水平数而不是值绘制的。平均值为 0.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")
第二个给出了正确的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")
有什么想法吗?我的坏主意是重新调整平均值,使其符合因子水平并使用第一个解决方案。如果某些因素水平“缺失”,这将无法正常工作,例如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 似乎不起作用。
如何获得我想要的一切?
- 密度总和为 1
- 居中高于值的条形
-
vline()号码正确 - 宽度=.5
使用基本图形,也许可以通过在 x 轴上绘制两次来解决这个问题。这里有类似的方法吗?
【问题讨论】: