为什么 floor_date 会阻止 geom_rect() 绘制?

Why does floor_date prevent geom_rect() to draw?

我想知道为什么这两个代码片段 不会产生相同的结果。为什么这两个图表不同?

library("ggplot2")
library("lubridate")

# This will draw a line only
a <- data.frame(
    day=c(floor_date(ymd_hms("2021/12/20 10:00:00"), unit="days"),
          floor_date(ymd_hms("2021/12/21 11:11:11"), unit="days")),
    start=c(10,20),
    end=c(50,60))
ggplot(a) + geom_rect(aes(xmin=day,xmax=day+1,ymin=start, ymax=end)) + geom_line(aes(x=day,y=start))

# This will draw a line *and* a rectangle
a <- data.frame(
    day=c(ymd("2021/12/20"),
          ymd("2021/12/21")),
    start=c(10,20),
    end=c(50,60))
ggplot(a) + geom_rect(aes(xmin=day,xmax=day+1,ymin=start, ymax=end)) + geom_line(aes(x=day,y=start))

编辑:将 day+0.5 替换为 day+1 以避免误导舍入问题。

day的class第一个例子是POSIXct,第二个例子是Date。 + 运算符做事不同:

library("lubridate")
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union

floor_date(ymd_hms("2021/12/20 10:00:00"), unit="days") + 0.5
#> [1] "2021-12-20 00:00:00 UTC"
ymd("2021/12/21") + 0.5
#> [1] "2021-12-21"

reprex package (v2.0.1)

于 2021-09-09 创建

第一个示例将引入宽度为 0 的条。