在ggplot2中添加图例

Adding legend in ggplot2

我看了类似的问题,感觉我已经做了所有的事情。仍然没有得到想要的输出。我正在使用 ggplot2tidyquant 包来可视化具有 2 个金融趋势的数据 我正在尝试显示包含趋势线颜色图的图例

data %>%
  ggplot(aes(date, price)) +
  geom_line() +
  geom_ma(ma_fun = SMA, n = 50, size = 1 , col = "red" , show.legend = TRUE)+
  geom_ma(ma_fun = SMA, n = 200, size = 1 , col = "blue", show.legend= TRUE)+
  theme_tq() 

给你:

library(tidyquant)
library(ggplot2)
data <- data.frame(date = 1:1000, price = cumsum(rnorm(1000)))
data %>%
  ggplot(aes(date, price)) +
  geom_line() +
  geom_ma(aes(color = 'MA50'),  ma_fun = SMA, n = 50, size = 1 ,show.legend = TRUE)+
  geom_ma(aes(color =  'MA200'), ma_fun = SMA, n = 200, size = 1 , show.legend = TRUE) +
  scale_colour_manual(name = 'Legend', 
                      guide = 'legend',
                      values = c('MA50' = 'red',
                                 'MA200' = 'blue'), 
                      labels = c('SMA(50)',
                                 'SMA(200)'))