Actually I have done much of the thing before I ask here and done lots of search but couldn't find the solution so far.
I have a subset of data that I need to fit each subset. On the other hand, when I try to plot regression lines of each of these subsets only one regression line is shown on the plot. That is the main problem so far.
Anyway lets go step by step;
here is a data.frame
xx <- rep(rep(seq(0,800,200),each=10),times=2)
yy<-c(replicate(2,sort(10^runif(10,-1,0),decreasing=TRUE)),replicate(2,sort(10^runif(10,-1,0),decreasing=TRUE)), replicate(2,sort(10^runif(10,-2,0),decreasing=TRUE)),replicate(2,sort(10^runif(10,-3,0),decreasing=TRUE)), replicate(2,sort(10^runif(10,-4,0), decreasing=TRUE)))
V <- rep(seq(100,2500,length.out=10),times=2)
No <- rep(1:10,each=10)
df <- data.frame(V,xx,yy,No)
from wide format to long format
library(reshape2)
df_new <- melt(df,id=c("No","xx","V"))
**fitting model
As <- 220
Ax <- 1500
model <- function(data){
nlsLM(value~ifelse(V<Vs, 1-exp(-D*(1-(xx-As)/Ax)^2*(1-V/Vs)^2),1),
data=data, start=c(D=1.21,Vs=1951),trace=T,control = nls.lm.control(maxiter=50))
}
library(plyr)
library(minpack.lm)
fit<- dlply(df_new, "No", .fun = model)
function for predicting fitting values ##from Adding Fitted Lines from an Existing Model
predictvals <- function(model, xvar, yvar, xrange=NULL, samples=10, ...) {
# If xrange isn't passed in, determine xrange from the models.
# Different ways of extracting the x range, depending on model type
if (is.null(xrange)) {
if (any(class(model) %in% c("nls", "glm")))
xrange <- range(model$model[[xvar]])
else if (any(class(model) %in% "loess"))
xrange <- range(model$x)
}
newdata <- data.frame(x = seq(xrange[1],xrange[2], length.out = samples))
names(newdata) <- xvar
newdata[[yvar]] <- predict(model, newdata = newdata, ...)
newdata
}
to form prediction lines that have the same x range across all groups
predvals<- ldply(fit, .fun=predictvals, xvar="V", yvar="value",xrange=range(df_new$V))
predvals$xx <- rep(rep(unique(df_new$xx),each=1),each=10)
and finally plot with facet_wrap~xx
ggplot(df_new,aes(y=value,x=V, col=factor(xx)))+
geom_point(size=3,alpha=.4)+
geom_line(data=predvals,aes(col=factor(xx)))+
scale_y_log10(breaks=c(1e-6,1e-5,1e-4,1e-3,1e-2,1e-1,1),limits = c(1e-6,1))+
facet_wrap(~xx,scales="free_x")
As
andAx
aren't defined. – Rorschach