1
votes

Say I have two datasets. One that contains two months of data:

units_sold <- data.frame(date = seq(as.Date("2017-05-01"), as.Date("2017-07-01"), 1), 
                     units = rep(20,62),
                     category = "units_sold")

And one that contains just a week:

forecast <- data.frame(date = seq(as.Date("2017-06-12"), as.Date("2017-06-18"), 1), 
                   units = 5,
                   category = "forecast")

I can put them on the same plot. I.e.,

joined <- rbind(units_sold, forecast)
ggplot(data = joined, aes(x=date, y=units, colour = category)) + geom_line()

enter image description here

However, I can't seem to figure out how to put a ribbon between the two lines. This is what I'm trying:

library(dplyr)
ribbon_dat <- left_join(forecast, units_sold, by = "date") %>%
              rename(forecast = units.x) %>%
              rename(units_sold = units.y) %>%
              select(-c(category.x, category.y))

ggplot(data = joined, aes(x=date, y=units, colour = category)) + 
geom_line() +
geom_ribbon(aes(x=ribbon_dat$date, ymin=ribbon_dat$forecast, ymax=ribbon_dat$units_sold))

I get this error: Error: Aesthetics must be either length 1 or the same as the data (69): x, ymin, ymax, y, colour

1

1 Answers

2
votes

You are very close, you need to pass the second dataset to the data argument in geom_ribbon().

ggplot(data = joined, aes(x = date)) + 
  geom_line(aes(y = units, colour = category)) +
  geom_ribbon(
    data = ribbon_dat,
    mapping = aes(ymin = forecast, ymax = units_sold)
  )