【问题标题】:How can i control bin intervals in ggplot2?如何控制 ggplot2 中的 bin 间隔?
【发布时间】:2017-01-24 13:18:54
【问题描述】:

我无法正确控制垃圾箱是否来自例如-10 到 +10 或从 0 到 20,当我说 binwidth = 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))

很奇怪,如果我使用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))

对于更大的数据集,我怎样才能让我的 bin 从 1..20、21..40 等开始?

【问题讨论】:

  • 另外,stat_bin 有一个用于完全控制的 breaks 参数。

标签: r ggplot2 histogram


【解决方案1】:

您可以通过使用geom_histogram 的参数center 来做到这一点,如下所示:

# 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))

通过指定 binwidth 和一个 bin 的中心,您可以定义 bin 的宽度应为 20 并以 11 为中心。因此第一个 bin 将是 1 到 21。

我还添加了一个 seq() 调用来构造 x 轴刻度,而无需手动输入所有刻度。结果图如下:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多