在ggplot中贴标签

时间:2017-07-10 22:50:14

标签: r ggplot2

我希望能够在ggplot中标记三条线图,每条线都有一个图例,因此在图表中我们可以判断哪条线与哪条线相关联。这是我目前的设置:

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

如何为A,B和C行创建图例?谢谢,

2 个答案:

答案 0 :(得分:3)

我认为这就是你想要的:

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

答案 1 :(得分:3)

您可以通过将数据从wide转换为long来以更短的方式执行此操作

library(tidyverse)
df %>% gather("var", "total", 2:4) %>% 
  ggplot(., aes(month, total, group = var, colour = var))+
  geom_line()

enter image description here