Alex
Alex

Reputation: 57

Alternate panel.background fill with white and grey

I want to create a line plot in ggplot2 that the panel background colors alternate between white and grey based on the X axis values.

In this case DOY is day of year and I would like for it to transition between each day.

I included some basic sample code. Basically want between DOY 1-2 to be white and DOY 2-3 to be grey and so forth.

Any help is appreciated, thanks in advance.

DOY <- c(1, 2, 3, 4, 5)
Max <- c(200, 225, 250, 275, 300)
sample <- data.frame(DOY, Max)

ggplot()+
  geom_line(data=sample, aes(x=DOY, y=Max), color = "black")

Upvotes: 1

Views: 1896

Answers (1)

neilfws
neilfws

Reputation: 33772

One way to approach this is to add a new variable (called e.g. stripe) to the data, which alternates based on the value of DOY. Then you can use that variable as the basis for filled, transparent rectangles.

I'm assuming that DOY is a sequence of integers with interval = 1, so we can assign on the basis of whether DOY is odd or even.

(Note: sample - not a great variable name as there's a function of that name).

library(dplyr)
library(ggplot2)

sample %>% 
  mutate(stripe = factor(ifelse(DOY %% 2 == 0, 1, 0))) %>% 
  ggplot(aes(DOY, Max)) + 
  geom_point() + 
  geom_rect(aes(xmax = DOY + 1, 
                xmin = DOY, 
                ymin = min(Max), 
                ymax = Inf, 
                fill = stripe), alpha = 0.4) + 
  scale_fill_manual(values = c("white", "grey50")) + 
  theme_bw() + 
  guides(fill = FALSE)

Result:

enter image description here

Upvotes: 2

Related Questions