【问题标题】:ggplot2 density histogram with width=.5, vline and centered bar positionsggplot2 密度直方图,宽度=.5,vline 和居中的条形位置
【发布时间】: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 轴上绘制两次来解决这个问题。这里有类似的方法吗?

【问题讨论】:

    标签: r ggplot2 histogram


    【解决方案1】:

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

    给了

    【讨论】:

    • 愚蠢的是我没有检查data.frame 来查看prop.table() 给出的类型。它输出character,然后data.frame() 将其转换为factor,因为stringsAsFactors=F 没有设置。
    • @Deleet 这个(某种程度上)的逆选项是在因子水平的加权平均值处绘制垂直线:with(d1,weighted.mean(as.integer(d.test),w = Freq))
    • @Joran 可能有效,但如果某些级别不存在(例如由于小数据集中的采样错误),它会给出奇怪的结果。
    • @Deleet 可能,但我认为只要频率总和为 1 就可以了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 2019-03-19
    相关资源
    最近更新 更多