2

Lets say I have some time series data that looks like this:

df <- data.frame(Month=seq(1,12),
                 Value = rnorm(12,0,1),
                 Season = c('Winter', 'Winter', 'Spring',
                            'Spring', 'Spring', 'Summer',
                            'Summer', 'Summer', 'Fall',
                            'Fall', 'Fall', 'Winter'))

I want to plot Value over time and show how it relates to Season. Plotting Value is easy, something like:

ggplot(data, aes(Month, Value)) + geom_line()

in ggplot or in base graphics:

plot(Value~Month, data=df, type='l')

What I'd like to do is compellingly overlay a factor. I would like to change the background color according to which month is on the x-axis. So, in my example, the left 1/6th would be, say white for winter, then the next third moving right would be yellow for spring, then the next third red for summer, etc, until rightmost 1/12th would be white again.

These seems like it should be something simple and easy for time series data, but I can't find any help on how to do this, in any graphics package. Any suggestions or insight would be appreciated!

Amadou Kone
  • 907
  • 11
  • 21
  • 2
    The `zoo` package offers the `xblocks()` function for both `ts` and `zoo` time series objects to facilitate these kind of displays. See `example(“xblocks“, package = “zoo“)`. – Achim Zeileis Jun 24 '15 at 22:05

2 Answers2

4

In base R you can do the following:

plot(Value~Month, type="n")
rect(df$Month-0.5, min(df$Value), df$Month+0.5, max(df$Value), col=df$Season, lty=0)
lines(Value~Month, data=df, type='l', col="orange", lwd=2)

And apologizing for the horrific base color schemes I'll put this here to illustrate:

Color Coded Background

And to do the same in ggplot2 you can do the following:

ggplot(df, aes(Month, Value, Season)) + 
  geom_rect(aes(NULL, NULL, 
    xmin=Month-0.5, xmax=Month+0.5, 
    ymin=min(Value), ymax=max(Value), 
    fill=Season
  )) + 
  geom_line()

Yielding the following:

enter image description here

Forrest R. Stevens
  • 3,435
  • 13
  • 21
0

Here's a start, using geom_rect, copied from here:

seasons <- data.frame(xstart = seq(0, 9, 3), xend = seq(3, 12, 3), col = letters[1:4])

ggplot() + geom_line(data = df, aes(x = Month, y = Value)) +
           geom_rect(data = seasons, aes(xmin = xstart, 
                     xmax = xend, ymin = -Inf, ymax = Inf, fill = col), alpha = 0.4)
Community
  • 1
  • 1
jeremycg
  • 24,657
  • 5
  • 63
  • 74