1

After I smoothed the plot with the qplot() function, I need to extract the new 'smoothed' data. I can't build a data frame from the smoothed data.

The plot is smoothed, but by building the data frame I get an error message.

I smoothed the plot with this

qq <- qplot(x4,y4, geom='smooth', span =0.5)

Afterwards, I tried this to build the data frame:

data.frame(qq) 

And I got the message :

Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) : 
  cannot coerce class ‘c("gg", "ggplot")’ to a data.frame
sudo make install
  • 5,629
  • 3
  • 36
  • 48
Nepto.py
  • 13
  • 2

2 Answers2

1

ggplot::geom_smooth uses different underlying functions to compute smooths, either depending on the size of the data set or the specifications of the user. For a small data set, it uses stats::loess, so you can get that information by running stats::loess yourself.

As an example, here's a smoothed ggplot based on the mtcars data set:

library(tidyverse)

plot.data <- ggplot(data = mtcars, aes(x = mpg, y = wt)) +
  geom_point() +
  geom_smooth(span = 0.5)
print(plot.data)

enter image description here

We can obtain that smooth ourselves by using loess and predict directly, and then packing that into a data frame:

loess.data <- stats::loess(wt ~ mpg, data = mtcars, span = 0.5)
loess.predict <- predict(loess.data, se = T)
loess.df <- data.frame(fit = loess.predict$fit, se = loess.predict$se.fit, mpg = mtcars$mpg, wt = mtcars$wt)


> head(loess.df)
                       fit        se  mpg    wt
Mazda RX4         2.851238 0.1746388 21.0 2.620
Mazda RX4 Wag     2.851238 0.1746388 21.0 2.875
Datsun 710        2.741055 0.1986979 22.8 2.320
Hornet 4 Drive    2.781686 0.1770399 21.4 3.215
Hornet Sportabout 3.454600 0.1967633 18.7 3.440
Valiant           3.592860 0.2072037 18.1 3.460

Which, as we can see by plotting it, is identical to what ggplot did on its own.

plot.fit <- ggplot(data = loess.df, aes(x = mpg, y = fit)) +
  geom_line() +
  geom_ribbon(aes(ymin = fit - se, ymax = fit + se), alpha = 0.5)
print(plot.fit)

enter image description here

jdobres
  • 11,339
  • 1
  • 17
  • 37
0

May be a more direct solution can be using stat_smooth

qq <- qplot(x4,y4, geom='smooth', span =0.5) + stat_smooth()
ghosh'.
  • 1,567
  • 1
  • 14
  • 19