'time series with specific date tick marks & labels
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:
Solution 1:[1]
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 reprex package (v2.0.1)
Solution 2:[2]
Your code doesn't work because you are passing a function to breaks
Just specify the breaks that you want as a vector of dates.
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 = seq.Date(from = as.Date("2016-09-21"),
to = as.Date("2021-03-21"),
by = "3 month")
) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
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))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DaveArmstrong |
| Solution 2 | Allan Cameron |


