ggplot直方图距离0值问题:与Excel及R hist()结果不一致
解决ggplot直方图与hist()/Excel频数不符的问题
问题根源
hist()函数通过breaks = seq(from=0,to=100,by=5)明确指定了从0起始、步长为5、到100截止的区间划分规则;而仅给geom_histogram()设置binwidth=5时,它会自动根据数据最小值确定区间起始点,导致区间划分逻辑和hist()/Excel不一致,最终频数统计出现偏差。
两种可行解决方案
方案1:用boundary参数对齐区间起始边界
设置boundary=0,强制每个bin的边界对齐0、5、10...这类刻度,和hist()的区间完全匹配:
ggplot(WPTD2, aes(x=Distance)) + geom_histogram(binwidth = 5, boundary = 0, fill = "skyblue") + labs(x = "Distance", y = "Number of Observations", title = "Distances of individual woodpigeons during sampling 1-4")
方案2:手动指定breaks序列
直接复用hist()里的breaks参数,确保区间划分完全一致:
ggplot(WPTD2, aes(x=Distance)) + geom_histogram(breaks = seq(from=0,to=100,by=5), fill = "skyblue") + labs(x = "Distance", y = "Number of Observations", title = "Distances of individual woodpigeons during sampling 1-4")
验证效果
运行上述任意一段代码后,ggplot生成的直方图区间划分、频数统计都会和hist()以及Excel的结果完全一致。
内容的提问来源于stack exchange,提问作者Eonear Black
相关产品推荐
相关产品推荐

