Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Labeling in ggplot

Tags:

r

ggplot2

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,

like image 241
Drthm1456 Avatar asked Oct 20 '25 11:10

Drthm1456


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

like image 114
Odysseus210 Avatar answered Oct 23 '25 00:10

Odysseus210


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

enter image description here

like image 28
shiny Avatar answered Oct 23 '25 00:10

shiny



Donate For Us

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