# Fitting curved lines to scatterplots in R

I have created a scatterplot. I want to see the trend of how the number of fishing cat scats vary with an increase in perimeter of water body. Hence my response variable is number of fishing cat scats and predictor variable is perimeter of water body. After creating a scatterplot, I gave an abline (lm) command, which has given me a linear regression line, which doesn't exactly portray the relationship between number of fishing cat scats and perimeter of water body. What command do I need to use to generate a curve which fits the data? I am using R as my statistical software.

-
The answers you got are fine; just suggesting that this sort of question may get a lot more views in SO. –  Carl Witthoft Jun 21 '14 at 12:27

I recommend using the ggplot2 package. The command geom_smooth() will add a line by default, which may result in . You can also plot a second- or third-order function using stat_smooth(formula=y~scale(x)+I(scale(x)^2)) (modify this formula to suit your model). Example:

perimeter=rgamma(999,100);catscats=rpois(999,5);require(ggplot2)             #Simulated data
ggplot(data.frame(catscats,perimeter),aes(x=perimeter,y=catscats))+          #Call plot
stat_smooth(method='glm',family='poisson',formula=y~scale(x)+I(scale(x)^2))+ #Plot GLM line
geom_smooth(col='red',se=F)+geom_point()         #Plot LOESS line in red and add scatterplot


BTW, I fit a Poisson regression line here, but a negative binomial model might be wiser for your data depending on the dispersion of cat scats. You may prefer a confidence band around the LOESS line.

-
Thank you so much. My data is zero inflated count data.........so after running the command it says "negative values not allowed for the 'Poisson' family"........what to do now? –  user48763 Jun 22 '14 at 7:22
Describe your new problem more specifically in a new question if you can't find another that already answers it. –  Nick Stauner Jun 22 '14 at 8:53

Here is another way to do this, using the same data (except for random variation) that @Nick used

perimeter=rgamma(999,100);
catscats=rpois(999,5);
df <- cbind(perimeter,catscats)
plot(perimeter,catscats)
lines(lowess(df))

-