Marking in ggplot

I want to be able to label three line plots in ggplot with a legend for each row, so in the plot we can determine which row is associated with which. Here's my current setup:

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 do I create a legend for lines A, B and C? Thank,

+3


source to share


2 answers


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

      



enter image description here

+3


source


You can make it shorter 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()

      



enter image description here

+3


source







All Articles