0

I want to add a non-linear regression line to a scatter plot in R. I've tried using the predict() command, but I have not been able to make it work for my data. My friend is doing it in Stata, where graph twoway qfit x y yielded a curved line, as I wanted in R. Is there such a function in R?

DespeRate
  • 25
  • 4
  • When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Mar 05 '18 at 15:46
  • Do you happen to know if I can upload a data set here, in some way? I don't know how to produce an example without that... – DespeRate Mar 05 '18 at 15:49
  • The link I provided gives suggestions for including data with your question. It doesn't have to be your actual data, just something we can easily use for testing. – MrFlick Mar 05 '18 at 15:51
  • @DespeRate did my solution work? – leeum Mar 06 '18 at 15:04
  • @leeum Yes! Sorry for not getting back yet, but yes, it worked marvelously! I have even been able to use that for a project I'm working on, so thank you for that! – DespeRate Mar 07 '18 at 16:35
  • @DespeRate great. Can you mark my answer as correct for future readers? Click the check mark – leeum Mar 07 '18 at 17:57

1 Answers1

0

Answer using library(ggplot2)

You want to use geom_smooth in your data. I believe method = 'gam' will give you a curved line. So if you have this below:

ggplot(data = df) + geom_scatter(aes(x = xvar, y = yvar))

You need to just add

ggplot(data = df) + geom_scatter(aes(x = xvar, y = yvar)) + 
geom_smooth(aes(x = xvar, y = yvar), method = 'gam')

See here for more info: http://ggplot2.tidyverse.org/reference/geom_smooth.html

leeum
  • 264
  • 1
  • 13