无法为我的图表添加标签

时间:2018-03-06 14:03:46

标签: r ggplot2

我有这张图: enter image description here

我只需要为每条彩色线条添加标签。 我需要添加蓝色预测销售和红色历史销售。 我试图调整这些例子here,但我有很多错误。此外,我无法使用此代码绘制上图:

使其可以再现:

 dput(df1)
structure(list(Semaine = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 
28, 29, 30, 31), M = c(5649.96284329564, 7400.19639744335, 6948.61488673139, 
5043.28209277238, 7171.29719525351, 7151.04746494067, 5492.96601941748, 
6796.1160130719, 5532.95496473142, 7371.33061889251, 5462.73861171367, 
7156.01570964247, 5558.63194819212, 9329.49289405685, 5770.02903225806, 
7348.68497576737, 5261.26655896607, 8536.11304909561, 7463.97630586968, 
6133.49774339136, 7252.69089929995, 6258.54674403611, 8167.67766497462, 
5644.66612816371, 7512.5169628433, 5407.84275713516, 7795.63220247711, 
5596.75282714055, 7264.37264404954, 5516.98492191707, 8188.80776699029 
> dput(df2)
structure(list(Semaine = c(32, 33.2, 34.4, 35.6, 36.8, 38), M = c(5820.32304669441, 
6296.32038834951, 7313.24757281553, 7589.714214588, 8992.35922330097, 
9664.95469255663)), .Names = c("Semaine", "M"), row.names = c(NA, 
-6L), class = "data.frame")

ggplot() + geom_line(data=df1, aes(x = Semaine, y = M),color = "red") + 
  stat_smooth(data=df2, aes(x = Semaine, y = M),color = "blue")+
  scale_x_continuous(breaks = seq(0,40,1))

谢谢!

1 个答案:

答案 0 :(得分:2)

cols <- c("A"="red", "B"="blue")
ggplot() + geom_line(data=df1, aes(x = Semaine, y = M,color = "A")) + 
  stat_smooth(data=df2, aes(x = Semaine, y = M,color = "B"), method = 'loess')+
  scale_x_continuous(breaks = seq(0,40,1)) +
  scale_color_manual(name="Title", values=cols)

enter image description here