R ggplot2 introduce slight smoothing to a line graph with only a few datapoints

前端 未结 2 620
滥情空心
滥情空心 2021-02-04 21:59

Not sure if this is a programming question or not...

If I have the data below, which produces a \'spiky\' chart, and I\'d like to produce a slightly smoothed one using g

相关标签:
2条回答
  • 2021-02-04 22:04

    If you want to avoid losing too much information from the data, below could be a better approach, that works good for large datasets:

    library(zoo)
    library(reshape)
    a$smooth<-rollmean(a$values,3,fill="extend") # 2nd parameter defines smoothness 
    ggplot(melt(a),aes(x=year,y=value,color=variable,group=variable))+geom_line()
    

    enter image description here

    Here is a better example:

    a <- data.frame(year=1:10,values=sin(1:10)+runif(10))
    a$smooth<-rollmean(a$values,3,fill="extend")
    ggplot(melt(a,id.vars="year"),aes(x=year,y=value,color=variable,
          group=variable))+geom_line(size=2)
    

    enter image description here

    0 讨论(0)
  • 2021-02-04 22:31

    You can try a polynomial. Since the x-axis variable has 12 unique values, you can use polynomials up to the 11th degree. Furthermore, you should use a continuos scale for the x-axis to achieve a smooth curve.

    Here's an example of an 8th-order polynomial:

    ggplot(a, aes(x = year, y = values, group = 1))+
      stat_smooth(aes(x = seq(length(unique(year)))), # continuous x-axis
                  se = F, method = "lm", formula = y ~ poly(x, 8)) +
      scale_x_continuous(breaks = seq(length(unique(a$year))), 
                         labels = levels(a$year)) # original labels
    

    Here, method = "lm" means, that a linear model is used. The second argument of the poly function specifies the degree. enter image description here

    0 讨论(0)
提交回复
热议问题