Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I want to create a line plot with the help of ggplot2 and I want to have the panel background colors alternate between white and grey based on the X-axis values.

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

I have also included some basic sample code:

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")

1 Answer

0 votes
by (107k points)

You can add a new variable (called e.g. stripe) to the data, which alternates based on the value of DOY. After that 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)

If you are a beginner and want to know more about R then do check out the R programming course

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...