Joe94
Joe94

Reputation: 145

Creating a second legend with ggplot?

I created the following plot using ggplot:

    y1 <- runif(20,-2,7)
    y2 <- c(-0.30306664,0.14744265 , 0.43857131 ,-0.04536794 ,-1.41432016,0.51887010 , 6.34925495 , 2.82511601 , 2.84251791, 4.05300569,-2.34208042, -0.29278747 , 0.49661933 , 0.75099908  ,1.12097713,2.72244949 , 2.23933230 , 1.86667714 , 2.17540024 , 7.56568823)
    x <- 2001:2020

ggplot() + 
  geom_rect(aes(xmin=2006.90, xmax=2009.15,ymin=-Inf,ymax=10, fill='blue'), alpha= 0.4)+geom_rect(aes(xmin=2019.80, xmax=Inf,ymin=-Inf,ymax=10, fill='orange'), alpha= 0.3)+geom_rect(aes(xmin=2009.90, xmax=2013.15,ymin=-Inf,ymax=10, fill="lightgreen"), alpha= 0.4)+
  geom_line(aes(x=x,y = y1),colour="black")+geom_line(aes(x=x,y = y2),colour="red")+
  geom_point(aes(x=x,y = y1),col="black")+
  geom_point(aes(x=x,y = y2),col="red")+
  theme_classic()+
  scale_fill_manual(name="",values = c("lightblue","lightgreen","orange"),labels=c(" R","k","C"))+theme(legend.position = "bottom")+ theme(axis.text.x = element_text(angle = 90))+geom_hline(yintercept = 0, color="black", size=1)

I have one legend to explain the content of the rectangles of the graph, but I need to add another legend to explain the two lines which are black and red. I wondered how to add another legend with a different position than the one that already exists to explain the names of the lines?

Can anyone help?

enter image description here

Upvotes: 2

Views: 1478

Answers (1)

stefan
stefan

Reputation: 125832

Move color inside aes, add scale_color_identity to get the right colors and to set the labels for the legend:

library(ggplot2)

ggplot() +
  geom_rect(aes(xmin = 2006.90, xmax = 2009.15, ymin = -Inf, ymax = 10, fill = "blue"), alpha = 0.4) +
  geom_rect(aes(xmin = 2019.80, xmax = Inf, ymin = -Inf, ymax = 10, fill = "orange"), alpha = 0.3) +
  geom_rect(aes(xmin = 2009.90, xmax = 2013.15, ymin = -Inf, ymax = 10, fill = "lightgreen"), alpha = 0.4) +
  geom_line(aes(x = x, y = y1, colour = "black")) +
  geom_line(aes(x = x, y = y2, colour = "red")) +
  geom_point(aes(x = x, y = y1, col = "black")) +
  geom_point(aes(x = x, y = y2, col = "red")) +
  scale_color_identity(name = NULL, labels = c(black = "Label 1", red = "Label 2"), guide = "legend") +
  theme_classic() +
  scale_fill_manual(name = "", values = c("lightblue", "lightgreen", "orange"), labels = c(" Rezession", "krise", "Corona 2020-")) +
  theme(legend.position = "bottom") +
  theme(axis.text.x = element_text(angle = 90)) +
  geom_hline(yintercept = 0, color = "black", size = 1)

enter image description here

Upvotes: 2

Related Questions