扩展 ggplot2 中日期的轴范围

Expanding the axis range for dates in ggplot2

我正在绘制多个时间序列图,需要有一个一致的 x 值范围(日期)来比较这些图。我尝试使用 expand_limits,但没有用。修复它的最佳方法是什么?我应该使用 continuous_scale 吗?

这会产生不同的范围:

library(ggplot2)

#Example Data
ID <- c(rep(1, 3), rep(2, 3))
date1 <- as.Date(c("2015-02-01", "2015-03-01", "2015-04-01", 
    "2015-03-01", "2015-03-15", "2015-03-31"), "%Y-%m-%d")
v1 <- rep(1:3, 2)
df <- data.frame(ID, date1, v1)
df

p1 <- ggplot(df[df$ID == 1,], aes(x = date1, y = v1)) +
    geom_point(size = 3, colour = "#0000FF")

p2 <- ggplot(df[df$ID == 2,], aes(x = date1, y = v1)) +
    geom_point(size = 3, colour = "#0000FF") 

plot(p1)
plot(p2)

这就是我尝试修复它的方式:

p2 <- ggplot(df[df$ID == 2,], aes(x = date1, y = v1)) +
        geom_point(size = 3, colour = "#0000FF") +
        expand_limits(x = c("2015-02-01", "2015-04-01"))

plot(p2)

这是错误:Error: Invalid input: date_trans works with objects of class Date only

谢谢!

尝试在 expand_limits 中添加 as.Date:

p2 <- ggplot(df[df$ID == 2,], aes(x = date1, y = v1)) +
      geom_point(size = 3, colour = "#0000FF") +
      expand_limits(x = as.Date(c("2015-02-01", "2015-04-01")))
print(p2)

只是为了提供另一个答案的替代方案,它解决了这个问题的目的,我宁愿使用 dplyr 包中的 dmy("01-02-2015"),我强烈建议使用它来简化日期处理对象。