I am trying to plot a time series using ggplot. I have aggregated monthly and weekly data for the last couple of years. I want my plot to show monthly data for five years until a certain cut-off. After this cut-off I want to show weekly data for one year. However, I want those two parts to be off the same horizontal length so that the weekly data can be seen in more detail. Is there a way to scale the x axis manually so that half of it covers a five-year period and the other half of it covers the adjacent one-year period?
I have tried to find an answer for a long-period of time and would be very grateful if somebody had an idea how to solve this.
Difficult to tell without a reproducible example, but it sounds like your data are probably something like this:
library(ggplot2)
set.seed(69)
df <- data.frame(dates = c(seq(as.POSIXct("2014-01-01"),
as.POSIXct("2018-12-01"), by = "1 month"),
seq(as.POSIXct("2019-01-01"), by = "1 week",
length.out = 52)),
values = (cumsum(runif(112, -0.4, 0.6)) + 10) * 1000)
ggplot(df, aes(dates, values)) + geom_line()
If you want your plot split into two panels, the easiest way to achieve this is to create a new column that denotes which panel you want each row to be in;
df$Period = as.factor(df$date > as.POSIXct("2019-01-01"))
levels(df$Period) <- c("Monthly (pre 2019)", "Weekly (2019")
Now you can just plot with facet_grid
according to your new factor:
ggplot(df, aes(dates, values)) +
geom_line() +
facet_grid(.~Period, scales = "free_x")
Created on 2020-07-15 by the reprex package (v0.3.0)