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