views:

409

answers:

1

Is there a way of overlaying a mathematical function on top of data using ggplot?

## add ggplot2
library(ggplot2)

# function
eq = function(x){x*x}

# Data                     
x = (1:50)     
y = eq(x)                                                               

# Make plot object    
p = qplot(    
x, y,   
xlab = "X-axis", 
ylab = "Y-axis",
) 

# Plot Equation     
c = curve(eq)  

# Combine data and function
p + c #?

In this case my data is generated using the function, but I want to understand how to use 'curve()' with ggplot. Thanks.

+7  A: 

You probably want stat_function:

library("ggplot2")
eq <- function(x) {x*x}
tmp <- data.frame(x=1:50, y=eq(1:50))

# Make plot object
p <- qplot(x, y, data=tmp, xlab="X-axis", ylab="Y-axis")
c <- stat_function(fun=eq)
print(p + c)

and if you really want to use curve(), i.e., the computed x and y coordinates:

qplot(x, y, data=as.data.frame(curve(eq)), geom="line")
rcs