Search code examples
rggplot2tidyquant

Adding legend in ggplot2


I have looked through similar questions and I have a feeling I have done everything. Still not getting the desire output. I am using ggplot2 and tidyquant packages to visualize data with 2 financial trends I am trying to display a legend that contains trends line 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


Solution

  • Here you go:

    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