Adding manual legend to ggplot2

@thisisdaryn 's solution is the tidiest way but if for some reason you need to use separate columns, you can set legends manually this way

library(ggplot2)
colors <- c("Sepal Width" = "blue", "Petal Length" = "red", "Petal Width" = "orange")

ggplot(iris, aes(x = Sepal.Length)) +
    geom_line(aes(y = Sepal.Width, color = "Sepal Width"), size = 1.5) +
    geom_line(aes(y = Petal.Length, color = "Petal Length"), size = 1.5) +
    geom_line(aes(y = Petal.Width, color = "Petal Width"), size = 1.5) +
    labs(x = "Year",
         y = "(%)",
         color = "Legend") +
    scale_color_manual(values = colors)

14 Likes