Kevin M
Kevin M

Reputation: 491

Expanding the axis range for dates in ggplot2

I am plotting a number of time series graphs and need to have a consistent x-value range (date) for comparison of the graphs. I tried to use expand_limits, but it didn't work. What's the best way to fix it? Should I be using continuous_scale?

This produces different ranges:

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)

This is how I'm trying to fix it:

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)

This is the error: Error: Invalid input: date_trans works with objects of class Date only

Thanks!

Upvotes: 4

Views: 2662

Answers (2)

Dar&#237;o
Dar&#237;o

Reputation: 11

Just to give an alternative to the other answer, which solves the aim of this question, I'd rather use dmy("01-02-2015") from dplyr package, which I strongly recommend to simplify working with date objects.

Upvotes: 1

user3710546
user3710546

Reputation:

Try with adding as.Date in expand_limits:

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)

enter image description here

Upvotes: 6

Related Questions