1

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! :)

Ivo
  • 3,890
  • 5
  • 22
  • 53

1 Answers1

0

Legends appear only for aesthetics. You need to pass color, fill, linetype, alpha, etc. etc. etc into your call to aes.

You can use either columns programmatically, i.e. pass unquoted column names (usually preferred), but you can also just pass a character string, which will then create a discrete aesthetic, which you can then scale as usual with scale_?aes_...

Below I just added title and label to the character vectors just to make it clear where the names come from.

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, lty = "myline-label")) + 
  geom_ribbon(data = t1, aes(x=x, y=y, ymin=ylo, ymax=yup, fill = "MyCI-label"), linetype=2, alpha=.15) + 
  geom_hline(linetype='dotted', yintercept = 0) + labs(y = "Y", x = "X") +
  geom_density(data = t2, aes(x = x, color="MyDens-label"), fill="lightblue", linetype="dashed") +
  scale_linetype("Myline-title") +
  scale_fill_discrete("MyCI-title") +
  scale_color_manual("MyDens-title", values = c("Darkblue"))

Created on 2021-04-07 by the reprex package (v1.0.0)

tjebo
  • 21,977
  • 7
  • 58
  • 94