为什么ggplot()的直方图仅与用于aes` fill的一个变量相同?

问题描述 投票:0回答:2

问题是关于与以下三个数字有关的两个观察结果:

((1)如果箱数相同,为什么(a)和(b)中的直方图不同?(2)(b)中的直方图与填充nonsmo的直方图完全相同。如果是这种情况,那么如何使用ggplot()制作完整数据的直方图?

((a)使用hist(chol$AGE,30)绘制。

Histogram using hist()

[(b)用ggplot(data=chol, aes(chol$AGE)) + geom_histogram()和默认值(即30 bin)绘制的直方图。

Histogram with ggplot()

((c)现在相对于变量SMOKE添加填充:

ggplot(data=chol, aes(chol$AGE)) + 
  geom_histogram(aes(fill = chol$SMOKE))

Histogram using ggplot() with fill.

r ggplot2 colors histogram fill
2个回答
0
投票

最有可能有大量的值与垃圾箱的上限和下限相匹配,因此根据偏好,无论是左开还是右开,垃圾箱都可能发生重大变化。

例如比较:

set.seed(10)
age<-as.integer(rnorm(100, 50, 20))
par(mfrow=c(2, 1))
hist(age, 30, right=TRUE)
hist(age, 30, right=FALSE)

enter image description here注意,仅创建了大约18个垃圾箱(垃圾箱宽度为5)

使用ggplot2,其中bin移至bin范围的中心:

library(ggplot2)
ggplot(data.frame(age), aes(age)) +geom_histogram()

enter image description here


1
投票

这是我在@ Dave2e发表评论后所做的事情

ggplot(data=chol, aes(AGE, fill = SMOKE)) + 
  geom_histogram(aes(y = ..count..), binwidth = 1, position = "stack")

hist(chol$AGE, breaks = 30, right = FALSE)

enter image description here

enter image description here

binwidth添加正确的值,默认情况下实现positionstack,并将right用作false可获得完全相同的直方图。

© www.soinside.com 2019 - 2024. All rights reserved.