2019-05-07

Plot a continuous series with ggplot2

Problem

When we try to plot a continuous series, in our example WS (Winter Solstice), ggplot2 connects the last winter data point in March to the first winter data point in December.

  • Data
library(ggplot2)

getSeason <- function(DATES) {
#found here https://stackoverflow.com/questions/9500114/find-which-season-a-particular-date-belongs-to
WS <- as.Date("2012-12-15", format = "%Y-%m-%d") # Winter Solstice
SE <- as.Date("2012-3-15",  format = "%Y-%m-%d") # Spring Equinox
SS <- as.Date("2012-6-15",  format = "%Y-%m-%d") # Summer Solstice
FE <- as.Date("2012-9-15",  format = "%Y-%m-%d") # Fall Equinox

# Convert dates from any year to 2012 dates
d <- as.Date(strftime(DATES, format="2012-%m-%d"))

ifelse (d >= WS | d < SE, "Winter",
  ifelse (d >= SE & d < SS, "Spring",
    ifelse (d >= SS & d < FE, "Summer", "Fall")))
}

zz <- sample(1:10000,365)/1000
dag <- seq(as.Date("2014-01-01"), as.Date("2014-12-31"), by = "day")
seas <-  getSeason(dag)
test <- data.frame(zz,dag,seas)

ggplot(data=test, aes(x=dag,ymax=zz,ymin=0,fill=seas))+
geom_ribbon()

Solution

We can solve it by subsetting our data in two, above and below WS, and plotting two layers with geom_ribbon. Thus you convert the continuous WS series into two discrete sections.

library(dplyr)
ggplot() +
  geom_ribbon(data = filter(test, dag >= "2014-12-15") ,
              aes(x = dag, ymax = zz, ymin = 0, fill = seas)) +
  geom_ribbon(data = filter(test, dag < "2014-12-15") ,
              aes(x = dag, ymax = zz, ymin = 0, fill = seas))

Results

References

No hay comentarios:

Publicar un comentario

Nube de datos