0

我使用 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)

我有一个图例来解释图形矩形的内容,但我需要添加另一个图例来解释黑色和红色的两条线。我想知道如何添加另一个位置与已经存在的位置不同的图例来解释线条的名称?

任何人都可以帮忙吗?

在此处输入图像描述

4

1 回答 1

1

color向内移动aes,添加scale_color_identity以获得正确的颜色并设置图例的标签:

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)

在此处输入图像描述

于 2021-06-08T13:15:55.590 回答