Home > other >  How to make a gap within a continuous time-series variable between years?
How to make a gap within a continuous time-series variable between years?

Time:05-01

I am trying to plot two time-series data with ggplot2, and add a break on purpose between two years. Here is the example code:

library(ggplot2)
library(xts)
ny=3
n = 365*ny
md = data.frame('Date' = as.Date('2001-01-01')   1:n -1, 
                'P' = rep(sin(seq(0, pi/2, length.out=365)), ny),
                'ET' = rep(sin(seq(0, pi/2, length.out=365)), ny)*0.8 )

mf = reshape2::melt(md, id='Date')
mf=cbind(mf, 'year' = as.numeric(substr(mf$Date, 1, 4)))


ggplot(data=mf) 
  geom_line(aes(x=Date, y=value, color=variable, grouping=year))

The line for ET and P are continuous at 12-31 to 01-1 of next year. How to make a gap between them? Thank you.

CodePudding user response:

One possible way to replicate the intent is to use facets for the years with different x-scales:

ggplot(data=mf) 
  geom_line(aes(x=Date, y=value, color=variable, grouping=year))   
  facet_grid(.~year, scales = "free_x")

CodePudding user response:

You could include or exclude the dates (choose one of the theme lines) and facet_wrap:

library(tidyverse)

ny <- 3
n <- 365 * ny
md <- data.frame(
  "Date" = as.Date("2001-01-01")   1:n - 1,
  "P" = rep(sin(seq(0, pi / 2, length.out = 365)), ny),
  "ET" = rep(sin(seq(0, pi / 2, length.out = 365)), ny) * 0.8
)

mf <- reshape2::melt(md, id = "Date")
mf <- cbind(mf, "year" = as.numeric(substr(mf$Date, 1, 4)))

mf |>
  ggplot(aes(Date, value, color = variable))  
  geom_line()  
  facet_wrap(~ year, nrow = 1, scales = "free_x")  
  # theme(axis.text.x = element_text(angle = 45, hjust = 1))   # Either with dates
  theme(axis.text.x = element_blank(), axis.ticks.x = element_blank())   # Or without dates
  labs(x = NULL)

Created on 2022-05-01 by the reprex package (v2.0.1)

  • Related