【问题标题】:r - hist function aggregates "zero" and "1" values into one bin.r - hist 函数将“零”和“1”值聚合到一个 bin 中。
【发布时间】:2014-08-11 12:32:11
【问题描述】:

我对 hist() 函数感到疯狂。我有一个数据集如下:

table(data)

0  1  2  3  4  5  7  8 
85  7  3  4  6  1  2  1 

所以我希望hist(data, labels=TRUE) 返回一个直方图,其中包含 9 个 bin,一个用于 0,一个用于 1,等等,每个 bin 都有一个值。但它聚合了 0 和 1,在谷歌上搜索一天后,我仍然无法弄清楚如何修复它。我还尝试声明像hist(data, breaks=c(0,8)) 这样的垃圾箱数量,但没有。 作为替代方案,我尝试使用lattice 包的histogram,它工作正常......但我无法弄清楚如何显示每个 bin 的值...... 无论哪种方式,您都可以帮助我吗(使用hist() 显示正确的列数或使用histogram() 显示bin 值)? 非常感谢。

【问题讨论】:

  • 试试hist(data,right=F)

标签: r histogram


【解决方案1】:

hist(...) 默认使用右闭区间。您可以使用 right=... 参数更改此设置。

x <- c(0, 1,  2,  3,  4,  5,  7,  8)
y <- c(85,  7,  3,  4,  6,  1,  2,  1)
z <- rep(x,times=y)

par(mfrow=c(1,2))
hist(z,right=T, main="Right closed")
hist(z,right=F, main="Left Closed")

这是ggplot 中的等价物,IMO 更清楚一点。

library(ggplot2)
ggplot(data.frame(z), aes(x=factor(z))) + 
  geom_histogram(fill="lightgreen", color="grey50")

【讨论】:

  • 非常感谢您的精彩解释!我更喜欢 ggplot2 :) 你知道我可以将条形的值放在每个条形的顶部(例如 hist(data, labels=TRUE) 的情况)吗?
猜你喜欢
  • 2016-06-27
  • 1970-01-01
  • 2018-10-12
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
相关资源
最近更新 更多