Skip to content
Prev 277051 / 398506 Next

plotting a function with given formula in ggplot2

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: