'How to change color of moving averages in ggplot, plotting two series into one graph?

In order to highlight the moving average in my ggplot visualization, I want to give it a different color (in this case grey or black for both MA lines). When it comes to to a graph representing two time series, I struggle to find the best solution. Maybe I need to take a different approach.

suppressPackageStartupMessages(library(tidyverse))
suppressPackageStartupMessages(library(tidyquant))

V = 365
data <- data.frame (var1 = c(rnorm(V)),
                    var2 = c(rnorm(V)+12),
                    date = c(dates <- ymd("2013-01-01")+ days(0:364))
                    )

data_melted <- reshape2::melt(data, id.var='date')

data_melted %>%
  ggplot() +
  geom_line(mapping = aes(x= date, y=value, col=variable)) +
  scale_color_manual(values=c("#CC6666", "steelblue")) +
  geom_ma(ma_fun = SMA, n = 30, mapping = aes(x= date, y=value, col=variable)) +  
  theme(axis.text.x = element_text(angle = 50, vjust = 0.5)) +
  scale_x_date(date_breaks = "1 month") 


Solution 1:[1]

I would consider looking at the tsibble library for time series data.

library(tsibble)

data_melted <-as_tsibble(data_melted, key = 'variable', index = 'date')

data_melted <- data_melted %>%
  mutate(
    `5-MA` = slider::slide_dbl(value, mean,
                .before = 2, .after = 2, .complete = TRUE)
  )

data_melted %>%
  filter(variable == "var1") %>%
  autoplot(value) + 
  geom_line(aes(y = `5-MA`), colour = "#D55E00") +
  labs(y = "y",
       title = "title") +
  guides(colour = guide_legend(title = "series"))

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hachiko