Construct manual legend in ggplot2

Hello!

I'm trying to show the discharge of three different rivers in 2005 on the same plot. However, a legend didn't pop up and I looked online to find ways to add a manual legend, but it isn't working.

Here's the plot:

Here is my code to get the plot and legend:

colors <- c("St Joseph" = "blue", "Kalamazoo" = "red", "Muskegon" = "darkgreen")
ggplot() + geom_line(data=stj05, aes(x=Date, y=Discharge_cfs), color="blue", size=1) + labs(title="Streamflow for St. Joseph, Kalamazoo, and Muskegon Rivers in 2005", color = "Legend") +
  coord_cartesian() + ylab("Discharge (cfs)") + geom_line(data=kal05, aes(x=Date, y=Discharge_cfs), color="red", size=1) +
    geom_line(data=mus05, aes(x=Date, y=Discharge_cfs), color="darkgreen", size=1) + scale_color_manual(values=colors)

Can anyone help me get a legend showing the individual rivers and their colors?

Thanks so much!

ggplot generates a legend when you map a variable to some aesthetic, like colour in this case. You can create "dummy" aesthetics, as in the first example below, but it's more natural to create one long data frame from your individual data frames (as in the second example below). Then you only need one call to geom_line and you can map a variable in your data to the colour aesthetic.

library(tidyverse)

# Set up fake data
mtcars$model = rownames(mtcars)

d1 = mtcars[ , c("model", "mpg", "hp")]
d2 = mtcars[ , c("model", "mpg", "wt")]

# Plot separate lines with "dummy" colour aesthetic
ggplot() +
  geom_line(data=d1, aes(mpg, hp, colour="hp")) + 
  geom_line(data=d2, aes(mpg, wt, colour="wt")) +
  labs(colour=NULL)

# Combine data frames to make one "long" data frame
d = left_join(d1, d2 %>% select(model, wt))
#> Joining, by = "model"

# Convert to "long" data frame
d = d %>% pivot_longer(c(wt, hp))
  
ggplot(d, aes(mpg, value, colour=name)) + 
  geom_line() +
  labs(colour=NULL)

Created on 2021-09-10 by the reprex package (v2.0.1)

1 Like

Perfect! That second one worked beautifully and was much more elegant. That pivot_longer() trick is awesome, thank you SO MUCH for your help!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.