Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlay multiple stat_function calls in ggplot2

I have two data frames raw and coef:

  • one containing raw data
  • the other containing modelling coefficients that I have derived from the raw data.

The first data frame raw contains :

  • Time (0 to 900 seconds)
  • OD for many Variants and four runs.

The second data frame coef contains :

  • one row per Variant/run combination, with the individual coefficients (M, D.1 and t0.1) in that row.

I have plotted the raw data split per Variant and colored by runID, without a problem. But, now I want to overlay the model curves according to the runID.

Since the modelling coefficients are in a different data frames, with different dimensions, I can't just cbind them. stat_function won't work for me. I can get only one curve showing at a time.

I have tried with a for loop, adding a stat_function layer each time:

p <- ggplot(temp, aes(Time, OD)) + geom_point(aes(colour = runID), size = 2) #works fine!
calc <- function(x){temp.n$M[ID] * (1 - exp(temp.n$D.1[ID] * temp.n$t0.1[ID] - x)))}
for(ID in 1:length(unique(temp.n$runID))) {
  p <- p + stat_function(fun = calc)
}
print(p)

At the end, all p returns is the plot of the raw data, and the final curve from the looping bit. p seems to revert to its original state every time I try to add a new stat_function layer.

Any ideas ?

like image 582
BenjaminH Avatar asked Jul 30 '10 13:07

BenjaminH


1 Answers

Following on the solution given here, you might have to imitate the effect of stat_function yourself. Since you do not give a reproducible example, I created a simple one that hopefully mimics your problem:

library(ggplot2)
reg.fun <- function(x, par1, par2){exp(-x*par1) + par2} #functional form
reg <- data.frame(g=factor(1:3), par1=(1:3)/10, par2=1:3)  #parameters for 3 groups

#generate data from reg.fun
dd <- expand.grid(x=0:9, g=reg$g)         #set x values, and 3 groups from reg
dd <- merge(dd, reg)                      #"import" parameters
dd$mn <- with(dd, reg.fun(x, par1, par2)) #value of function for given x's
dd$y <- rnorm(30, mean=dd$mn, sd=0.5)     #add variability
dd <- subset(dd, select=c(g,x,y))         #remove auxiliary variables 

#similarly to above generate values for the function on a fine grid of x values
pred.dd <- expand.grid(x=seq(0,9, length=101), g=levels(dd$g))
pred.dd <- merge(pred.dd, reg)
pred.dd$y <- with(pred.dd, reg.fun(x, par1, par2))

#draw the plot
p <- qplot(x,y, colour=g, data=dd)  #scatterplot of data
p + geom_line(data=pred.dd)         #add the curves of the functions 
like image 138
Aniko Avatar answered Sep 16 '22 23:09

Aniko