I have a plot containing a line plot with confidence interval (geom_ribbon()
) and an additional density plot of the underlying data (from a different data frame).
I would like to add a legend with three entries: for the line, the confidence interval, and the density.
Consider the following MWE: (in t1
, ylo
and yup
mark the CI, y
the line, and t2
contains the data for the density plot.
(I tried incorporating code from this question to no avail.)
library(tidyverse)
t1 <- tibble(x = c(0:22)) %>%
mutate(ylo = c(seq(from = .25, to = 1.35, length.out=10), seq(from = 1.35, to = -1.22, length.out=13)),
y = .25 * x + 1,
yup = c(seq(from = 2.75, to = 4.5, length.out=10), seq(from = 4.75, to = 12, length.out=13)))
t2 <- tibble(x = rnorm(100000, 10, 1))
ggplot() +
geom_line(data = t1, aes(x=x, y=y)) +
geom_ribbon(data = t1, aes(x=x, y=y, ymin=ylo, ymax=yup), linetype=2, alpha=.15) +
geom_hline(linetype='dotted', yintercept = 0) + labs(y = "Y", x = "X") + theme_bw() +
geom_density(data = t2, aes(x = x), color="darkblue", fill="lightblue", linetype="dashed") +
scale_color_manual(values = c("#000000", "grey60", "lightblue"), name = "Title") + # from other answer; couldn't get it to work
coord_cartesian(ylim = c(-0.0125, 12.5), xlim = c(-0.5, 22))
Many thanks for any pointers! :)