My problem is that I have some stock prices(numbers) that are plotted against dates(strings). Now I have an indicator variable. I would like to shade the area on the graph for those dates where the indicator is 1 and not shade when it is 0. I'm programming in R. I know how to do it for a prespecified interval for example 2000-01-01 to 2001-01-01. But I have many "intervals" where the indicator variable shows 1 and I would prefer not to count them myself. Any ideas on how to overcome this obstacle? I would like it to be through ggplot2 if possible.
Example of my data:
data <- data.frame(
date = as.Date(c("2001-01-01", "2001-01-02", "2001-01-03",
"2001-01-04","2001-01-05","2001-01-06", "2001-01-07",
"2001-01-08","2001-01-09","2001-01-10")),
price = c(623.3,515.2,611.0,729.0,843.25,623.3,515.2,611.0,729.0,843.25),
indicator = c(1,1,1,0,0,0,1,1,1,0)
)
NOTE: I've asked this question before, but it got marked as a duplicate. I do not consider it so, since I cannot find any other post that actually answers my question. I've seen others with the same question, but the answers are always to specify your own range to shade, which it is not the purpose here.
CodePudding user response:
The answer is that you need to use your data to create the shaded background areas.
library(ggplot2)
background_df <- data[data$indicator == 1,]
background_df$end <- background_df$date lubridate::days(1)
ggplot(data, aes(date, price))
geom_rect(ymin = -Inf, ymax = Inf, aes(xmin = date, xmax = end),
data = background_df, fill = "deepskyblue4", alpha = 0.2)
geom_line(colour = "orange3")
geom_point()
theme_bw()
Created on 2022-03-06 by the reprex package (v2.0.1)