组合 "aes" 和 "manual" 比例以在 ggplot 中创建图例(两个数据框)

Combine "aes" and "manual" scales to create legend in ggplot (two data frames)

我想向图例添加两个比例:一个来自数据框并使用“aes”,第二个来自另一个数据框和“手动”。我在代码中标记了我认为应该修改的地方。谢谢!

  1. 加载包

    library(tidyverse)
    library(RColorBrewer)
    
  2. 创建假数据

    dd <- data.frame(Year = rep(2005:2021, 2),
                     Balance = c(rep("Output", 17), rep("Input", 17)),
                     Total = c(runif(17, min = 100, max = 200), 
                               runif(17, min = -99, max = -10)))
    drs <- filter(dd, Year %in% c(2005, 2010, 2015, 2020)) %>%
      arrange(Year, Balance) %>%
      group_by(Year) %>%
      mutate(diff = cumsum(Total)) %>%
      ungroup()
    
  3. 构建情节我需要在图例中包含虚线

     ggplot() + 
          geom_bar(data = dd,
                   stat = "identity", aes(x = Year, y = Total, fill = Balance)) +
          geom_line(data = filter(drs, Balance == "Output"), 
                    aes(x = Year, y = diff), size = 1) +
          geom_point(data = filter(drs, Balance == "Output"), 
                     aes(x = Year, y = diff), size = 2) +
          scale_fill_brewer(name = "", palette = "Blues") +
          scale_size_manual(name = "Balance2", values = diff) + #Here is where I have issues
          theme_bw() +
          theme(text = element_text(size = 21))
    
    

像这样?

您可以为您的 geom_linegeom_point 美学提供一种颜色来映射。然后使用scale_colour_manual调整颜色和名称。

dd <- data.frame(Year = rep(2005:2021, 2),
                 Balance = c(rep("Output", 17), rep("Input", 17)),
                 Total = c(runif(17, min = 100, max = 200), 
                           runif(17, min = -99, max = -10)))
drs <- filter(dd, Year %in% c(2005, 2010, 2015, 2020)) %>%
  arrange(Year, Balance) %>%
  group_by(Year) %>%
  mutate(diff = cumsum(Total)) %>%
  ungroup()


ggplot() + 
  geom_bar(data = dd,
           stat = "identity", aes(x = Year, y = Total, fill = Balance)) +
  geom_line(data = filter(drs, Balance == "Output"), 
            aes(x = Year, y = diff, colour = Balance), size = 1) +
  geom_point(data = filter(drs, Balance == "Output"), 
             aes(x = Year, y = diff, colour = Balance), size = 2) +
  scale_fill_brewer(name = "", palette = "Blues") +
  scale_colour_manual(values = c("black"), name = "Balance2") + #Here is where I have issues
  theme_bw() +
  theme(text = element_text(size = 21))