You can download the https://stats.idre.ucla.edu/wp-content/uploads/2016/02/hsb2-1.csv data frame that will be used in these examples.

Suppose that we would like to overlay two different plots in one single trellis graph. For example, we would like to overlay two plots consisting of a scatter plot with a regression line, but in each graph we would like to have a different dependent and independent variable. In one trellis graph we would like to have a scatter plot and regression line of

readregressed onwrite, and a scatter plot and regression line ofscienceregression onmathboth conditional on the variableses.

Reading in the

hsb2data frame.

hsb2 <- read.table('https://stats.idre.ucla.edu/wp-content/uploads/2016/02/hsb2-1.csv', header=T, sep=",")

Also, you will need to load the package

latticebefore you start. You can downloadlatticefrom the CRAN website from within R by clicking on “Packages” and then “Install package(s) from CRAN”.

library(lattice)

Let’s first look at how we would generate each trellis graph individually.

#creating a factor variable ses.f from the variable ses hsb2$ses.f <- factor(hsb2$ses, label=c("low", "medium", "high")) xyplot(write~read | ses.f, hsb2, panel=function(x, y){ panel.xyplot(x, y, pch=16) panel.lmline(x, y, lty=4) }, as.table=T)

xyplot(math~science | ses.f, hsb2, panel=function(x, y){ panel.xyplot(x, y, pch=3) panel.lmline(x, y) }, as.table=T)

In order to combine the two graphs we will make use of the

subscriptparameter, which is a parameter in every panel function. Thesubscriptparameter is an indicator of which indices corresponds to which panel in the trellis graph. Thus, we include thesubscriptparameter in the function we create for thepanelargument in the trellis graph. Since we want to have two scatter plots overlaid, we must have twopanel.xyplotfunctions; likewise, we want to have two regression lines in each plot, and therefore we must include twopanel.lmlinefunctions. One of thepanel.xyplotfunction will use the variables specified in theformulaargument (write~read|ses.f) of thexyplotfunction which indicates which observation will be used in each of the panels. In the otherpanel.xyplotfunction we need to use thesubscriptparameter to indicate which observations will be used in each of the panels because we are no longer using the variables in the formula given in theformulaargument in thexyplotfunction.

xyplot(write~read | ses.f, hsb2, panel=function(x, y, subscripts){ panel.xyplot(x, y, pch=16) panel.lmline(x, y, lty=4) panel.xyplot(hsb2$science[subscripts], hsb2$math[subscripts], pch=3) panel.lmline(hsb2$science[subscripts], hsb2$math[subscripts]) }, as.table=T, subscripts=T)