在ggplot2中添加图例

时间:2018-04-09 11:55:02

标签: r ggplot2 tidyquant

我查看了类似的问题,我感觉自己已经做了一切。仍未获得欲望输出。我正在使用 ggplot2 tidyquant 软件包来显示包含2个金融趋势的数据我试图显示包含趋势线coloron plot的图例

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

enter image description here

1 个答案:

答案 0 :(得分:1)

你走了:

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

enter image description here