为什么 `ggplot()` 的直方图与仅用于 `aes` `fill` 的一个变量相同?
Why histogram from `ggplot()` is same as for only for one variable used for `aes` `fill`?
问题是关于与以下 3 个数字相关的两个观察结果:
(1) Why the histograms in (a) and (b) are different if number of bins is same?
(2) Histogram in (b) is exactly same as the histogram for the fill nonsmo
. If this is the case then how to make histogram of complete data using ggplot()?
(a) 使用 hist(chol$AGE,30)
.
绘图
(b) 使用 ggplot(data=chol, aes(chol$AGE)) + geom_histogram()
和默认值绘制的直方图,即 30 个 bin。
(c) 现在添加关于变量的填充 SMOKE
:
ggplot(data=chol, aes(chol$AGE)) +
geom_histogram(aes(fill = chol$SMOKE))
很可能有大量值与 bin 上限和下限相匹配,因此根据偏好,无论是左开还是右开,bin 都可能发生重大变化。
例如比较:
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)
注意,只创建了大约 18 个 bin(bin 宽度为 5)
使用 ggplot2,其中 bin 移动到 bin 范围的中心:
library(ggplot2)
ggplot(data.frame(age), aes(age)) +geom_histogram()
这是我在@Dave2e 发表评论后所做的
ggplot(data=chol, aes(AGE, fill = SMOKE)) +
geom_histogram(aes(y = ..count..), binwidth = 1, position = "stack")
hist(chol$AGE, breaks = 30, right = FALSE)
为 binwidth
添加正确的值,默认实现 position
是 stack
并使用 right
作为 false
得到完全相同的直方图。
问题是关于与以下 3 个数字相关的两个观察结果:
(1) Why the histograms in (a) and (b) are different if number of bins is same?
(2) Histogram in (b) is exactly same as the histogram for the fillnonsmo
. If this is the case then how to make histogram of complete data using ggplot()?
(a) 使用 hist(chol$AGE,30)
.
(b) 使用 ggplot(data=chol, aes(chol$AGE)) + geom_histogram()
和默认值绘制的直方图,即 30 个 bin。
(c) 现在添加关于变量的填充 SMOKE
:
ggplot(data=chol, aes(chol$AGE)) +
geom_histogram(aes(fill = chol$SMOKE))
很可能有大量值与 bin 上限和下限相匹配,因此根据偏好,无论是左开还是右开,bin 都可能发生重大变化。
例如比较:
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)
使用 ggplot2,其中 bin 移动到 bin 范围的中心:
library(ggplot2)
ggplot(data.frame(age), aes(age)) +geom_histogram()
这是我在@Dave2e 发表评论后所做的
ggplot(data=chol, aes(AGE, fill = SMOKE)) +
geom_histogram(aes(y = ..count..), binwidth = 1, position = "stack")
hist(chol$AGE, breaks = 30, right = FALSE)
为 binwidth
添加正确的值,默认实现 position
是 stack
并使用 right
作为 false
得到完全相同的直方图。