考虑以下两个图
library(ggplot2)
set.seed(666)
bigx <- data.frame(x=sample(1:12,50,replace=TRUE))
ggplot(bigx, aes(x=x)) +
geom_histogram(fill = "red", colour =
"black",stat="bin",binwidth=2) +
ylab("Frequency") +
xlab("things") +
ylim(c(0,30))
hist(bigx$x)


为什么我在ggplot上得到了高于12的悬垂?当我使用right = TRUE时,这只是将悬垂转移到零以下。我希望在使用ggplot2的情况下从hist()获得简单且简单的绑定结果。
我该怎么做呢?
发布于 2014-12-09 01:29:04
如果您的目标是使用ggplot重现hist(...)的输出,则可以这样做:
ggplot(bigx, aes(x=x)) +
geom_histogram(fill = "red", colour = "black",stat="bin",
binwidth=2, right=TRUE) +
scale_x_continuous(limits=c(0,12),breaks=seq(0,12,2))

或者,更一般地说,这是:
brks <- hist(bigx$x, plot=F)$breaks
ggplot(bigx, aes(x=x)) +
geom_histogram(fill = "red", colour = "black",stat="bin",
breaks=brks, right=TRUE) +
scale_x_continuous(limits=range(brks),breaks=brks)显然,直方图的ggplot默认设置是使用右闭合间隔,而hist(...)的默认设置是左闭合间隔。此外,ggplot使用不同的算法来计算x轴折断和限制。
https://stackoverflow.com/questions/27362344
复制相似问题