0

The example code is the following (it may have no sense statistically, but the problem is the object not found). While next works:

mtcars %>% ggplot(aes(x = vs, y = mpg)) + geom_smooth(method="lm")

Next does not:

> mtcars %>% ggplot(aes(x = vs, y = mpg)) + geom_smooth(method=lm(weights = cyl))
Error in stats::model.frame(weights = cyl, drop.unused.levels = TRUE) : 
  object 'cyl' not found

Why this error? What can I do to solve it?

I also tried

> mtcars %>% ggplot(aes(x = vs, y = mpg)) + geom_smooth(method=lm(weights = "cyl"))
Error in terms.formula(formula, data = data) : 
  argument is not a valid model

and other variants with "", with more info inside lm, etc., but without success.

Thank you very much!

iago
  • 2,990
  • 4
  • 21
  • 27
  • 2
    Try this... `geom_smooth(aes(weight = cyl), method = "lm")` – Andrew Gustar Oct 10 '19 at 10:35
  • 2
    Possible duplicate of [Adding a weighted least squares trendline in ggplot2](https://stackoverflow.com/questions/42507098/adding-a-weighted-least-squares-trendline-in-ggplot2) – nghauran Oct 10 '19 at 10:38
  • As pointed out by @AndrewGustar, [specify weights in the `weight` aesthetic](https://books.google.fr/books?id=XgFkDAAAQBAJ&pg=PA63&lpg=PA63&dq=geom_smooth+with+weights&source=bl&ots=so3-bM8-bS&sig=ACfU3U39iFlL1E196khn6Ta4gpRTvVn18A&hl=fr&sa=X&ved=2ahUKEwiqqPLpvpHlAhU7DWMBHXtlB5AQ6AEwBnoECAgQAQ#v=onepage&q=geom_smooth%20with%20weights&f=false) – nghauran Oct 10 '19 at 10:41
  • This is similar to your question https://stackoverflow.com/questions/20240350/custom-lm-formula-in-geom-smooth – Mr.Rlover Oct 10 '19 at 10:41
  • I had seen already https://stackoverflow.com/questions/42507098/adding-a-weighted-least-squares-trendline-in-ggplot2 and I felt like it didn't work. Thank you! – iago Oct 10 '19 at 11:02

1 Answers1

0
mtcars %>% ggplot(aes(x = vs, y = mpg)) +  
   stat_smooth(method="lm", aes(weight= cyl))

This will generate a graph, but I am not sure if it is what you after. weight here may not different from the weights you wanted to use.

Zhiqiang Wang
  • 6,206
  • 2
  • 13
  • 27