为 R 的 Date 和 POSIXct 计算不同的美学

Count aesthetics differently calculated for R's Date and POSIXct

我在处理 DatePOSIXct 对象时注意到一些非常奇怪的事情。见以下代码:

library(tidyverse)
library(Rmisc)

test <- structure(list(
  date = structure(c(
    16863, 16866, 16862, 16743,
    16741, 16819, 16820, 16969, 16896, 16636, 16855, 16715, 16842,
    16899, 16859, 16860, 16827, 16823, 16912, 16878, 16848, 16839,
    16901, 16833, 16896, 16841, 16735, 16800, 16781, 16903
  ), class = "Date"),
  group = structure(c(
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L,
    2L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L,
    2L, 1L, 2L, 2L, 2L
  ), .Label = c("0", "1"), class = "factor")
), row.names = c(
  NA,
  -30L
), class = c("tbl_df", "tbl", "data.frame"))

test$posix <- as.POSIXct(test$date)

p1 <- ggplot(
  test, 
  aes(x = date, group = group, colour = group, fill = group)
) + 
  stat_density(aes(y = ..count..), alpha = 0.4)

p2 <- ggplot(
  test, 
  aes(x = posix, group = group, colour = group, fill = group)
) + 
  stat_density(aes(y = ..count..), alpha = 0.4)

multiplot(p1, p2)

结果如下图:见 y 轴。 (计数 < 1 因为样本量太小。)

当调用 geom_density..count.. 时,为什么这两个图的比例会不同?调用 ..density.. 时相同。两个情节之间的唯一区别是用 DatePOSIXct 呼吁 x 美学。我很纳闷。

啊,这是个很愚蠢的问题。傻我。

> as.numeric(test$posix)
 [1] 1456963200 1457222400 1456876800 1446595200 1446422400
 [6] 1453161600 1453248000 1466121600 1459814400 1437350400
[11] 1456272000 1444176000 1455148800 1460073600 1456617600
[16] 1456704000 1453852800 1453507200 1461196800 1458259200
[21] 1455667200 1454889600 1460246400 1454371200 1459814400
[26] 1455062400 1445904000 1451520000 1449878400 1460419200

> as.numeric(test$date)
 [1] 16863 16866 16862 16743 16741 16819 16820 16969 16896 16636
[11] 16855 16715 16842 16899 16859 16860 16827 16823 16912 16878
[21] 16848 16839 16901 16833 16896 16841 16735 16800 16781 16903

所以正如@hrbrmstr所说,这只是单位的问题。

我将此 post 作为警告,以表明转换为 POSIXct class 可能会产生意想不到的后果。当时我(不必要地)尝试使用 scale_x_datetime