0

I have a dataframe called blueshade in R, and I would like to shade certain background regions a time series interactive plot of this dataframe. I am trying to use plotly and ggplot Below is the code I have written so far.

months<-c("2007-05-01","2008-01-01","2009-01-01", "2010-01-01", "2011-01-01")
numbers<-c(1,8,50,11,3)
blueshade<-data.frame(months, numbers)
blueshade$months<-as.Date(blueshade$months)

p<-
ggplot(blueshade)+
  geom_line(mapping=aes(x=months, y=numbers))

ggplotly(p)

If I would like to shade the region between 2007-05-01 and 2008-01-01 RED, and shade the region between 2009-01-01 and 2011-01-01 BLUE, does anyone know how I would write such code in R? I also want the shading to be somewhat transparent.

James Rider
  • 633
  • 1
  • 9
  • Do you mean shade the background region between those dates, or shade the area between the x-axis and the line? – nrennie Jul 11 '23 at 21:56
  • Closely related if not duplicate: https://stackoverflow.com/questions/63951513/fill-background-intervals-in-ggplotly-line-graph – Jon Spring Jul 11 '23 at 22:47
  • The tricky part is `ggplotly` doesn't seem to have the same way to specify `ymin = -Inf, ymax = Inf` to get the full displayed range. If a manual solution ok, you could use `geom_rect(aes(xmin = start, xmax = end, ymin = 0, ymax = 55, fill = my_fill), data = data.frame(start = as.Date(c("2007-05-01", "2009-01-01")), end = as.Date(c("2008-01-01", "2011-01-01")), my_fill = I(c("red", "blue"))), alpha = 0.2) +` as your first layer. – Jon Spring Jul 11 '23 at 22:49

0 Answers0