Home > Mobile >  time series with specific date tick marks & labels
time series with specific date tick marks & labels

Time:05-13

I have time series data, with data points for each season turn (mar 21st, jun 21st, sept 21st & dec 21st) between 2016 and 2020. I am trying to plot this data but it insists on setting tick labels starting October 19th.

How do I get the tick marks and labels to correspond to the dates in the data set? (e.g. tick marks at 2016-09-21, 2016-12-21, 2017-03-21 ...)

Here is the code for the plot, specifying tick marks every 3 months.

ggplot(meltdf,aes(x=date,y=value,colour=variable,group=variable))  
  geom_line()   
  xlab("")  
  theme_ipsum()  
  scale_x_date(date_labels = "%Y %b %d", #date_breaks = "3 month",
               breaks = function(x) seq.Date(from = min(x), 
                                             to = max(x), 
                                             by = "3 month")
              )  
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

And here is the graph:

time series with wrong tick labels

CodePudding user response:

How about this:

library(tidyverse)
dat <- expand.grid(
  month = c(3, 6, 9, 12), 
  day = 21, 
  year = 2016:2020)

set.seed(123)
dat <- dat %>% 
  mutate(date = lubridate::ymd(paste(year, month, day, sep="-")), 
         y = rnorm(length(date)))

ggplot(dat, aes(x=date, y=y))   
  geom_line()   
  xlab("")  
  theme_minimal()  
  scale_x_date(date_labels = "%Y %b %d", breaks = unique(dat$date))   
  theme(axis.text.x = element_text(hjust=1, vjust = .5, angle=90))

Created on 2022-05-12 by the enter image description here


Data used

meltdf <- data.frame(date = rep(seq.Date(from = as.Date("2016-09-21"), 
                                     to = as.Date("2021-03-21"), 
                                     by = "3 month"), each = 2),
                     value = runif(38, 1, 5),
                     variable = rep(c("var1", "var2"), length.out = 38))
  • Related