Search code examples
rggplot2timeserieschart

Label X-Axis as Year in Correlogram


I am trying to plot a correlogram of time series data but cannot label the X-Axis as years.

set.seed(1)
ts1 <- truncnorm::rtruncnorm(42, a=5.717151, b=18.765000, mean=18.736, sd=16.31536)
ts <- ts(ts1, start = 1980, end = 2022, frequency = 1)

ggplot(NULL, aes(y = ts, x = seq_along(ts))) + scale_x_continuous(breaks = seq(1980,2022,3)) +
  geom_line(color = "#F2AA4CFF") + geom_point(color = "#101820FF") + xlab('Year') + ylab('Inflation Rate (in %)') + #ggtitle(expression("(a)\nsd = 1\n"~phi~"=.8")) + 
  theme(axis.text = element_text(size = 10, angle = 0, vjust = 0.0, hjust = 0.0), axis.title = element_text(size = 10), axis.title.x = element_text(angle = 0, hjust = 0.5, vjust = 0.5, size = 10), axis.title.y = element_text(angle = 90, hjust = 0.5, vjust = 0.5, size = 14), plot.title = element_text(size = 14, margin = margin(t = 25, b = -20, l = 0, r = 0))) + 
  scale_y_continuous(expand = c(0.0, 0.00)) + ggplot2::theme_bw()

This is what I have as a plot

What I Want

I want the X-Axis to be labeled as year starting from 1980 to 2022 with a convinient space inbetween. I tried using + scale_x_continuous(breaks = seq(1980,2022,1)) but the lebel does not show up in the plot.

Update

I am thinking that lubridate package can help without writing to much functio.


Solution

  • Convert timeseries object into a dataframe then plot:

    d <- data.frame(Y = as.matrix(ts), date = time(ts))
    
    ggplot(d, aes(y = Y, x = date)) +
      geom_line() +
      geom_point() + 
      scale_x_continuous(breaks = seq(1980, 2022, 1))
    

    (Note, I removed irrelevant aesthetic bits of code to the problem)

    enter image description here