r - ggplot2 密度直方图,宽度 =.5,vline 和中心条位置

标签 r ggplot2 histogram

我想要一些离散数据的良好密度(总和为 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")

enter image description here

第二个给出了正确的 vline() 放置(因为 x 轴是连续的),但是错误的条形放置和 width 参数似乎不是当 x 轴连续时可修改 ( 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() 在正确的数字处
  • 宽度=.5

有了基础图形,也许可以通过在 x 轴上绘制两次来解决这个问题。这里有类似的方法吗?

最佳答案

听起来你只是想确保你的 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

关于r - ggplot2 密度直方图,宽度 =.5,vline 和中心条位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30040348/

相关文章:

r - 在 R 中通过多个 .csv 文件循环代码

r - 删除或隐藏数据点的标签

r - 如何获取 ROC 曲线中 x 轴(FPR)和 y 轴(TPR)的值

r - 使用 ggmap 设置背景 map 的不透明度

来自不同数据文件的 gnuplot 聚类直方图

r - 分类/二进制数据总和的直方图

r - 使用 ggplot2 拟合 nls - 类型为 'symbol' 的错误对象不是可子集化的

r - 如何有条件地突出显示ggplot2构面图中的点-将颜色映射到列

r - 在ggplot2中的条之间放置刻度线

python - 根据其他列值选择值