【问题标题】:How to make histogram in ggplot2 start at zero on X axis? [duplicate]如何使ggplot2中的直方图在X轴上从零开始? [复制]
【发布时间】:2021-06-16 08:02:59
【问题描述】:

当使用geom_histogram() 绘制直方图时,绘图始终不会像预期的那样从零开始。请参阅下面的示例:

set.seed(20) 
randomnum <- rnorm(40) 
data <- data.frame(number = randomnum[randomnum > 0]) 
ggplot(data, aes(x = number)) +  
  geom_histogram(color="black", fill="grey40")

即使数据不包含负数,直方图也会从负值开始。下面的代码可能会看得更清楚:

ggplot(data, aes(x = number)) +
  geom_histogram(color="black", fill="grey40", binwidth = 0.1) +
  scale_x_continuous(breaks = c(0, seq(0, 2, 0.1)))

直方图将从-0.1开始,但原始数据不包含负数据。
我理想的绘图是 x 轴将从 0 开始,并且每个绘图条共享相同的宽度。剧情可能是这样的:

stackoverflow 中有一些类似的问题,link1link2。他们更改了scale_x_continuous() 中的参数。但它只会改变轴刻度和标签,并不能解决我的问题。

【问题讨论】:

标签: r ggplot2 plot


【解决方案1】:

好的,解决方法是:

ggplot(data, aes(x = number)) +
  geom_histogram(color="black", fill="grey40", binwidth = 0.1, 
                 boundary = 0, closed = "left") +
  scale_x_continuous(breaks = c(0, seq(0, 2, 0.1)))

boundary 是关键参数!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 2016-06-05
    相关资源
    最近更新 更多