[R] Lattice: raw data and prediction of a non linear fitted function

Kevin Wright kw.stat at gmail.com
Thu Aug 6 22:42:32 CEST 2015


I find this type of lattice graph to be much easier to create via the
use of layers in the latticeExtra package.  See the "carmer.density"
dataset example in the "agridat" package, which shows the use of
layers.  It doesn't have "groups", but it is not too hard to add a
groups argument to a layer and then use latticeExtra to combine
layers.

Kevin Wright


On Wed, Aug 5, 2015 at 7:24 AM, François Collin <fanch.collin at gmail.com> wrote:
> Dear all,
>
> I have a question about lattice use. I would like to use it to represent:
> - my raw data as points,
> - and the results of a non linear fit as a line,
> - having 2 groups data (and so 2 colors).
>
> However, as I have few raw data, I would like to increase the number of
> points to smooth the line which correspond to the fit.
>
> So my questions are:
> - How can I use the group argument to make new predictions inside panel
> argument ?
> - How can I use this prediction inside the panel argument to draw the fit
> per group?
>
> Hereafter a minimal example:
>
> #==================================================
> library(lattice)
> set.seed(2)
>
> # Dummy dataframe
> foo <- data.frame(
>   time = seq(0, 60, 5),
>   char = sample(c("A", "B"), size = 13, replace = TRUE)
>   );
>
> # Simulated response vector according a Gompertz function + rnorn(0, 5)
> foo$y <- SSgompertz(foo$time, Asym = 100, b2 = ifelse(foo$char == 'A', 6,
> 10),
>   b3 = ifelse(foo$char == "A", .91, .8)) +
>   rnorm(nrow(foo), mean=0, sd = 5);
>
> # Non-linear fit on simulation data
> res_nls <-  nls(
>   y ~ SSgompertz(time, Asym = 100, b2[char], b3[char]), data = foo,
>   start = list( b2 = c(7,7), b3 = c(0.9, 0.9)));
>
> # My problem
> xyplot(y ~ time, groups = char, data = foo,
>   panel = function(x, y, groups=groups, model = model, ...){
>     panel.xyplot(x,y, groups = groups, ...);
>
>     newdata <- data.frame(time = x, char = groups);
>     newdata$y <- predict(model, newdata = newdata);
>
>     panel.superpose(x = newdata$time, y=newdata$y,  groups = groups, ...,
>       panel.groups = function(x,y, col, col.symbol, ...){
>         panel.lines(x,y, col.line = col.symbol)
>       })
>
>   }, model = res_nls);
> #==================================================
>
>
> Many thanks,
> Francois
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



-- 
Kevin Wright



More information about the R-help mailing list