Skip to content

plotting a function with given formula in ggplot2

2 messages · Curiouslearn, Dennis Murphy

#
Hi All,

I have a scatter plot produced using ggplot2 and I want to add the
regression line to this scatter plot. I suppose I can use
geom_smooth() to do this, but for the sake of learning ( I am new both
to R and ggplot2), I want to try and add it as a function (something
that curve() does in the standard R plotting). I did some search and
found that stat_function() can be used for this. But somehow it is not
working. The following is my code. Can you please tell me where I am
going wrong and what the correct code would be:

reg1 <- lm(kid_score ~ mom_hs, data=iqdata)

scatter  <-  ggplot() + geom_point(data=iqdata,

aes(x=as.factor(mom_hs), y=kid_score) )
                               + xlab("Mother's High School Status")
                               + ylab("Children's Test Score")
                               + stat_function(fun=function(x)
coef(reg1)[1] + coef(reg1)[2] * x)

I understand that you probably do not have the data I am using (I am
trying this out from Gelman Hill's book on Multilevel models). But I
was hoping you may be able to point out the error without the data.

Thanks for your help.
#
Hi:

Borrowing from this thread, courtesy of Brian Diggs:
http://groups.google.com/group/ggplot2/browse_thread/thread/478f9e61d41b4678/ed323c497db61156?lnk=gst&q=stat_function#ed323c497db61156

...here's a small reproducible example:

ddf <- data.frame(x = 1:10, y = 0.4 + 0.6 * (1:10) + rnorm(10))
# Find the linear model coefficients
lmc <- coef(lm(y ~ x, data = ddf))
# Create a function to produce the fitted line
lmeq <- function(x) lmc[1] + lmc[2] * x

# Construct the ggplot() and use stat_function():
ggplot(ddf, aes(x = x, y = y)) +
    geom_point() +
    stat_function(fun = lmeq, colour = 'red', size = 1)

HTH,
Dennis
On Thu, Nov 10, 2011 at 10:47 AM, Curiouslearn <curiouslearn at gmail.com> wrote: