How to get smoothed data as a vector?

How to get smoothed data as a vector?

For example, I draw a graph

ggplot2::ggplot(data=data.frame(x=seq(1,28),y=data$Var1), aes(x, y)) +
geom_point() +
geom_smooth(method = "loess", se = FALSE, span=0.3, n=28)

however, I don't understand how to extract the result as a vector

The best way to get your data smoothed is to use stats::loess function directly rather than have ggplot do it for you

1 Like
# package libraries 
library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 4.2.2
#> Warning: package 'ggplot2' was built under R version 4.2.3
#> Warning: package 'tibble' was built under R version 4.2.3
#> Warning: package 'tidyr' was built under R version 4.2.2
#> Warning: package 'readr' was built under R version 4.2.2
#> Warning: package 'purrr' was built under R version 4.2.2
#> Warning: package 'dplyr' was built under R version 4.2.3
#> Warning: package 'stringr' was built under R version 4.2.2
#> Warning: package 'forcats' was built under R version 4.2.2
#> Warning: package 'lubridate' was built under R version 4.2.2

# sample data 
set.seed(9)

df <- tibble(
  x = seq(1, 28, 1),
  var1 = rnorm(n = 28, mean = 1, sd = .1)
)

# apply stats::loess function directly 
df <- df %>%
  mutate(
    m = predict(loess(var1 ~ x))
  )

# view
df
#> # A tibble: 28 × 3
#>        x  var1     m
#>    <dbl> <dbl> <dbl>
#>  1     1 0.923 0.923
#>  2     2 0.918 0.943
#>  3     3 0.986 0.960
#>  4     4 0.972 0.975
#>  5     5 1.04  0.988
#>  6     6 0.881 0.999
#>  7     7 1.12  1.01 
#>  8     8 0.998 1.01 
#>  9     9 0.975 1.02 
#> 10    10 0.964 1.02 
#> # ℹ 18 more rows

Created on 2023-08-16 with reprex v2.0.2

Thank you very much for your answer! But I think they have different default settings. I liked the result of the "loess" function from "ggplot2" more than from "stats" when I tried to solve the problem. I'll try again as you suggested.

Thank you very much for your answer! Everything is clear, now I'll try, similar code!

ps. Is it really impossible to get a result from ggplot2? I rummaged through the structure of the returned object, but found nothing.

The default result of stats::loess is really bad. How to remove the shift and improve anti-aliasing?

x<-seq(1,28)
var1<-data$Trechus.secalis
var1
 [1]  0  0  0  1  1  5  2  8  5  5  0  3  1  0  3  5  1  2  1  0  2 12  0  2  3  0
[27]  2  0

plot(x,var1,pch=19,cex=1)
j <- order(var1)
l<-loess(var1~x)
lines(x,l$fitted[j],col="red",lwd=3)

l<-predict(loess(var1 ~ x,span=0.3))
lines(x,l,col="cyan",lwd=3)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.