You can create trend lines or regression lines through data. These can be useful when using lattice plots in R. When you tell lattice to calculate a line of best fit, it does so for each panel in the plot. This is straightforward using xyplot(), because it’s as simple as adding a type argument.

In particular, you want to specify that the type is both points (type = p) and regression (type = r). You can combine different types with the c() function, like this:

> xyplot(mpg ~ hp | cyl, data = transform.mtcars,
+    type = c("p", "r"))

Your graphic should look like this.

Lattice <span class=
xyplot with regression lines added." width="535"/>
Lattice xyplot with regression lines added.

Strictly speaking, type is not an argument to xyplot(), but an argument to panel.xyplot(). You can control the panels of lattice graphics with a panel function. The function xyplot() calls this panel function internally, using the type argument you specified. The default panel function for xyplot() is panel.xyplot().

Similarly, the panel function for barchart() is panel.barchart(). The panel function allows you to take fine control over many aspects of your chart. You can find out more in the excellent Help for these functions — for example, by typing ?panel.xyplot into your R console.

About This Article

This article is from the book:

About the book authors:

Andrie de Vries is a leading R expert and Business Services Director for Revolution Analytics. With over 20 years of experience, he provides consulting and training services in the use of R. Joris Meys is a statistician, R programmer and R lecturer with the faculty of Bio-Engineering at the University of Ghent.

This article can be found in the category: