I have a ggplot with 3 ribbons. I can produce this plot with the following code:
library(ggplot2)
library(RColorBrewer)
data <- data.frame(
date = seq.Date(as.Date("2018-01-01"), as.Date("2018-01-31"), by= "days"),
value = runif(min = 0, max = 1, n = 31)
)
breaks <- c(0.1, 0.2, 0.3)
reds <- brewer.pal(3, "Reds")
pl <- ggplot2::ggplot(data = data,
aes(x = date, y = value)) +
geom_ribbon(
aes(
x = date,
ymin = value * (1 - breaks[1]),
ymax = value * (1 + breaks[1])
),
fill = reds[3],
alpha = 0.4
) +
geom_ribbon(
aes(
x = date,
ymin = value * (1 - breaks[2]),
ymax = value * (1 + breaks[2])
),
fill = reds[2],
alpha = 0.4
) +
geom_ribbon(
aes(
x = date,
ymin = value * (1 - breaks[2]),
ymax = value * (1 + breaks[2])
),
fill = reds[1],
alpha = 0.4
) +
geom_line(size = 1); pl
This works perfectly and does what I want.
My question is how can I generalize the amount of ribbons in my code. If I want to add a new ribbon I can copy/paste my code but that's not what I want... I would like only to extend the breaks-vector (c(0.1, 0.2, 0.3, 0.4)) and then the plot should contain automatically 4 ribbons (or even more). In my case the later plot will be produced by a function. This function should only contain the breaks (and data) as parameters.
I thought I can do this with a for-loop around the geom_ribbon and store the the results an a list. But I didn't succeeded :-(
Have anybody an idea? Thanks a lot in advance!