user3047435
user3047435

Reputation: 161

Cannot add legend with multiple geom_line

I can't seem to be able to get the legend to work. I tried to change the data format but having the geom_ribbon complicates things a bit. Any help is much appreciated!

Thanks!

library(ggplot2)

Year <- c(2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012)
hi <- c(5.9, 5, 5, 4.9, 6.1, 5.9, 5.8, 6.2, 6.4)
lo <- c(4, 4, 3.8, 3.9, 4.5, 4.3, 4.1, 3.9, 3.7)
A <- c(4.4, 4.3, 4.7, 4.5, 5.5, 5.2, 5.4, 4.8, 4.4)
B <- c(4.7, 4.6, 4, 4.1, 4.7, 4.6, 4.4, 4.6, 4.8)
C <- c(0.61, 0.31, 0.13, 0.18, 0.24, 0.44, 0.32, 0.5, 0.4)
test <- data.frame(Year, hi, lo, A, B, C)

ggplot(test, aes(Year)) +
  geom_ribbon(aes(ymin = lo , ymax = hi), fill = "grey90") +
  geom_line(aes(y = A), colour= "black", size = 1) +
  geom_line(aes(y = B), colour = "#55BF3B", size = 1) +
  geom_line(aes(y = C), colour = "#f15c80", size = 1) +
  ggthemes::theme_hc() +
  scale_x_continuous(labels = abs, limits = c(2004, 2012), breaks = seq(2004, 2012, 4)) +
  scale_colour_manual("", values = c("A" = "black", "B" = "#55BF3B", "C" = "#f15c80"))

Upvotes: 0

Views: 3480

Answers (1)

tyluRp
tyluRp

Reputation: 4768

You could try the following:

library(ggplot2)
library(dplyr)
library(tidyr)

# A named vector that represents the colors for each line (to be used in scale_color_manual)
cols <- c("A" = "black", "B" = "#55BF3B", "C" = "#f15c80")

test %>% 
  gather(key, value, -c(Year, hi, lo)) %>% 
  ggplot(aes(Year)) +
  geom_ribbon(aes(ymin = lo, ymax = hi), fill = "grey90") +
  geom_line(aes(y = value, group = key, color = key), size = 1) +
  scale_colour_manual(values = cols) +
  ggthemes::theme_hc()

enter image description here

The line:

cols <- c("A" = "black", "B" = "#55BF3B", "C" = "#f15c80")

Isn't required since ggplot2 will automatically give each line it's own color but in case you want to set it manually you would add the line above and include:

scale_colour_manual(values = cols)

Somewhere near the end of the ggplot2 chain.

Upvotes: 1

Related Questions