I have a time series data with a gap of year (e.g. 2006). I attempted to create a continuous lineplot ignoring this gap with scale_x_date. However, the function only removes the date labels on the x-axis and leaves a gap in the plot. Is there a way to remove the x-axis text and the gap in datapoints?
Data:
set.seed(123)
n <- 100
y <- sample.int(n, replace=TRUE)
t <- seq(from=as.Date("2001-01-01"), by="month", length.out=n)
dat <- data.frame(t, y)[!format(t, "%Y") %in% 2006, ]
Tried:
library(ggplot2)
my_break_fun <- function(x){
br <- seq(from = min(x), to=max(x), by="2 month")
br[!format(br, "%Y") %in% 2006]
}
dat |>
ggplot(aes(x=t, y=y)) +
geom_line() +
scale_x_date(
date_labels="%b-%Y",
breaks=my_break_fun
) +
theme(axis.text.x = element_text(angle=90, hjust=1, vjust=1))

Facets would be one common way:
dat |>
dplyr::mutate(grp = t >= as.Date("2006-01-01")) |>
ggplot(aes(x=t, y=y)) +
geom_line() +
scale_x_date(
date_labels="%b-%Y",
breaks=my_break_fun
) +
facet_grid(.~grp, scales = "free_x", space = "free_x") +
theme(axis.text.x = element_text(angle=90, hjust=1, vjust=1)) +
theme(strip.background = element_blank(),
strip.text = element_blank())

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