Search code examples
rggplot2moving-average

3 point moving average on a multi line plot


I have a ggplot graph that has several functions graphed on it. I would like to smooth each line using a three point moving average. How can I go about going through that? This is my image: Image of pre-smooth graph

This is some of my data:

YEAR       Topic     Perct
1981         A         40
1981         B         12
1981         C         12
1982         A         38
1982         B         8
1982         C         14
1983         A         39
1983         B         13
1983         C         18
1984         A         40
1984         B         11
1984         C         13 
1985         A         42
1985         B         9
1985         C         15 
1986         A         44
1986         B         11
1986         C         14       
1987         A         42
1987         B         13
1987         C         18
1988         A         40
1988         B         12
1988         C         18
1989         A         42
1989         B         11
1989         C         19  
1990         A         39
1990         B         10
1990          C         18

Solution

  • You could use zoo::rollmean. Here I have also plotted the original points to show how the original data compares to the rolling mean.

    library(tidyverse)
    library(zoo)
    
    df %>%
      group_by(Topic) %>%
      mutate(Rolling_Mean = rollmean(Perct, 3, fill = NA)) %>%
      ggplot(aes(x = YEAR, y = Rolling_Mean, color = Topic)) +
      geom_point(aes(y = Perct), alpha = 0.3, size = 3) +
      geom_line(size = 1, na.rm = TRUE) +
      theme_minimal(base_size = 16) +
      scale_x_continuous(breaks = 1980:1990) +
      ylim(c(0, 50)) +
      labs(x = NULL, y = "Percentage (rolling mean)") +
      scale_color_brewer(palette = "Set1")
    

    enter image description here