voi*_*nyx 4 r histogram ggplot2
当我说binwidth = 20我得到前者时,我无法正确控制 bin 是从 -10 到 +10 还是从 0 到 20,但我有从 1 开始的数据,我不希望间隔进入负数。
这是我的问题的一个例子:
testData = data.frame(x=c(1,4,6,9,9))
ggplot(data=testData, aes(x=testData$x)) +
geom_histogram(binwidth=3, aes(col=I("white"))) +
scale_x_continuous(breaks=c(1,2,3,4,5,6,7,8,9,10))
Run Code Online (Sandbox Code Playgroud)
很奇怪,如果我使用,binwidth = 2我最终会得到我想要的间隔:
ggplot(data=testData, aes(x=testData$x)) +
geom_histogram(binwidth=2, aes(col=I("white"))) +
scale_x_continuous(breaks=c(1,2,3,4,5,6,7,8,9,10))
Run Code Online (Sandbox Code Playgroud)
对于更大的数据集,如何让我的 bin 从 1..20、21..40 等开始?
您可以通过使用参数做到这一点center的geom_histogram,如下所示:
# Make some random test data
testData = data.frame(x=runif(1000,min=1,max=110))
# Construct the plot
ggplot(data=testData, aes(x=testData$x)) +
geom_histogram(binwidth=20,
center = 11,
aes(col=I("white"))) +
scale_x_continuous(breaks=seq(1,max(testData$x) + 20, by = 20))
Run Code Online (Sandbox Code Playgroud)
通过指定 binwidth 和一个 bin 的中心,您可以定义 bin 的宽度为 20,并以 11 为中心。因此第一个 bin 将是 1 到 21。
我还添加了一个seq()调用来构建 x 轴刻度,而无需手动键入所有刻度。结果图如下: