I want to be able to label three line graphs in ggplot with a legend for each line so on the graph we can tell which line associates with what. Here is my current set up:
ggplot(Months, aes(x = Month_Num)) +
geom_line(aes(y = A), colour = "blue") +
geom_line(aes(y = B), colour = "green") +
geom_line(aes(y = C), colour = "red")+
ylab(label = "Total") +
xlab("Month Num") +
ggtitle("Total by Month Num")
How can i create a legend for line A, B and C? Thanks,
I think this is what you want:
df <- data.frame(month = 1:5,
A = 1:5,
B = 6:10,
C = 11:15)
ggplot(df, aes(x = month)) +
geom_line(aes(y = A, col = "A")) +
geom_line(aes(y = B, col = "B")) +
geom_line(aes(y = C, col = "C")) +
ylab(label= "Total")

You can do this in a shorter way by converting the data from wide to long
library(tidyverse)
df %>% gather("var", "total", 2:4) %>%
ggplot(., aes(month, total, group = var, colour = var))+
geom_line()

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With