2

I'd like to add two scales to a legend: one from a data frame and using "aes" and a second one from another data frame and "manual". I've marked in the code what I think should be modified. Thanks!

  1. Load packages

    library(tidyverse)
    library(RColorBrewer)
    
  2. Create fake data

    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. Build plot I NEED TO INCLUDE THE DOTTED LINE IN THE LEGEND

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

enter image description here

user3262756
  • 649
  • 1
  • 9
  • 27

1 Answers1

1

like this?

You can feed your geom_line and geom_point aesthetics a colour to map to. Then use scale_colour_manual to adjust the colour and name.

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

QAsena
  • 603
  • 4
  • 9
  • Exactly it! Many thanks! So, I had to identify what line and point had in common, in this case "colour" and then set the value in "scale_colour_manual". Great! :) – user3262756 Jan 08 '21 at 10:52
  • 1
    Great! Gets pretty confusing... could probably work in another couple of ways: https://stackoverflow.com/questions/14622421/how-to-change-legend-title-in-ggplot – QAsena Jan 08 '21 at 11:29