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!
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)

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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With