Reputation: 41
I am trying to recreate the following plot.
But no matter what I do, my X-axis marks are starting from 1965 instead of 1963. Here is the graph plot I obtain.
Here is my code:
ggplot(dulles, aes(Index, Passengers)) +
geom_line() +
geom_point(color = "red") +
ylim(0, 25000) +
scale_x_date(limits = as.Date(c("1963", "2015"), format = "%Y"), date_breaks = "5 years", date_labels = "%Y")
As you can see, I have set the limits argument, but they're not being displayed.
I also tried replacing date_breaks = "5 years", date_labels = "%Y")
with breaks = as.Date(as.character(seq(1963, 2015, 5)), format = "%Y")
which was probably stupid anyway.
I want the X-axis labels to begin from 1963 and end in 2013 but without removing the data points for 2014 and 2015, just like in the original plot.
How can I do it?
Upvotes: 1
Views: 2782
Reputation: 76605
To define a breaks vector is a simple way to enforce axis tick marks.
library(ggplot2)
breaks.vec <- seq(min(df1$Index), max(df1$Index), by = "5 years")
ggplot(df1, aes(Index, Y)) +
geom_line() +
geom_point(color = "red") +
scale_x_date(breaks = breaks.vec, date_labels = "%Y")
Test data creation code
set.seed(2021)
Index <- seq(as.Date("1963-01-01"), as.Date("2015-12-31"), by = "1 years")
Y <- cumsum(rnorm(length(Index)))
df1 <- data.frame(Index, Y)
Upvotes: 2