[R] lattice plot: points and lines for different variables in same plotlattice plot

Naresh Gurbuxani naresh_gurbuxani at hotmail.com
Sun Oct 4 21:30:22 CEST 2015


I want to draw scatter plot and a fitted line in the same lattice plot.  My problem is that either both can be plotted as points or both as lines.  The code that attempts to plot points for data and lines for fitted line does not work.  

Thanks,
Naresh

library(lattice)
library(plyr)

my.df <- data.frame(x = rnorm(100), y = rnorm(100), name = "A")

temp.df <- data.frame(x = rnorm(100), name = "B")
temp.df <- within(temp.df, {y <- x + 0.2 * rnorm(100)})
my.df <- rbind(my.df, temp.df)

temp.df <- data.frame(x = rnorm(100), name = "C")
temp.df <- within(temp.df, {y <- x + 0.5 * x^2 + 0.2 * rnorm(100)})
my.df <- rbind(my.df, temp.df)

my.df <- ddply(my.df, c("name"), mutate, y.fit = lm(y ~ x + I(x^2))$fitted.values)

my.df <- my.df[order(my.df$name, my.df$x),]

# This works
xyplot(y + y.fit ~ x | name, data = my.df, type = c("l"))

# This does not work.  Line plot seems wrong.
xyplot(y + y.fit ~ x | name, data = my.df, type = c("l"), y.prime = my.df$y.fit, panel = function(x, y, y.prime, ...){panel.xyplot(x, y); panel.lines(x, y.prime, type = "l")})


 		 	   		  
	[[alternative HTML version deleted]]



More information about the R-help mailing list