Search code examples
rdatetimeggplot2facet-wrapposixlt

Points not aligned on x-axis of ggplot 1-column facet wrap


Please kindly check and advice on how I can resolve the difference in the two plots generated by the following script:

time1 <- c(
  as.POSIXlt("2021-05-02 23:57:29"),
  as.POSIXlt("2021-05-02 23:58:29"),
  as.POSIXlt("2021-05-02 23:59:29"),
  as.POSIXlt("2021-05-03 11:06:00"),
  as.POSIXlt("2021-05-03 11:07:00"),
  as.POSIXlt("2021-05-03 11:08:00")
)
time2 <- c(
  as.POSIXlt("2021-05-02 23:59:29"),
  as.POSIXlt("2021-05-02 23:59:29"),
  as.POSIXlt("2021-05-02 23:59:29"),
  as.POSIXlt("2021-05-03 11:08:00"),
  as.POSIXlt("2021-05-03 11:08:00"),
  as.POSIXlt("2021-05-03 11:08:00")
)

grp <- c("A","B","C","A","B","C")
cnt <- c(29,1,30,31,2,33)

df1 <- data.frame(time1, grp, cnt)
df2 <- data.frame(time2, grp, cnt)

p1 <- ggplot(df1, aes(x = time1, y = cnt, color = grp)) +
  geom_jitter(size = 1.0, show.legend = FALSE) +
  facet_wrap(~grp, ncol = 1, shrink = FALSE)

p2 <- ggplot(df2, aes(x = time2, y = cnt, color = grp)) +
  geom_jitter(size = 1.0, show.legend = FALSE) +
  facet_wrap(~grp, ncol = 1, shrink = FALSE)

Plot p1 shows the points as aligned as per their time1 values. In plot p2 the points are not aligned.

Plot p1

Plot p2


Solution

  • When you type ?geom_jitter, you will see that there would be a random variation to the point location:

    The jitter geom is a convenient shortcut for geom_point(position = "jitter"). It adds a small amount of random variation to the location of each point, and is a useful way of handling overplotting caused by discreteness in smaller datasets.

    To have deterministic layout, you should use geom_point, which gives you enter image description here