The Lattice Plotting System in R The Lattice Plotting System in R

-xyplot: this is the main function for creating scatterplots -bwplot: box-and-whiskers plots (“boxplots”) -histogram: histograms -stripplot: like a boxplot but with actual points -dotplot: plot dots on “violin strings” -splom: scatterplot matrix; like pairs in base plotting system -levelplot, contourplot: for plotting “image” data

#install.packages('lattice')
#xyplot(y ~ x | f * g, data)
library(lattice)
library(datasets)
## Simple scatterplot
xyplot(Ozone ~ Wind, data = airquality)

library(datasets)
library(lattice)
## Convert 'Month' to a factor variable
airquality <- transform(airquality, Month = factor(Month))
xyplot(Ozone ~ Wind | Month, data = airquality, layout = c(5, 1))

Lattice graphics functions return an object of class trellis and autoprints the object to the graphic device.

p <- xyplot(Ozone ~ Wind, data = airquality) ## Nothing happens!
print(p) ## Plot appears

Lattice functions have a panel function which controls what happens inside each panel of the plot.

set.seed(10)
x <- rnorm(100)
f <- rep(0:1, each = 50)
y <- x + f - f * x + rnorm(100, sd = 0.5)
f <- factor(f, labels = c("Group 1", "Group 2"))
xyplot(y ~ x | f, layout = c(2, 1)) ## Plot with 2 panels

## Custom panel function
xyplot(y ~ x | f, panel = function(x, y, ...) {
 panel.xyplot(x, y, ...) ## First call the default panel function for 'xyplot'
 panel.abline(h = median(y), lty = 2) ## Add a horizontal line at the median
})

## Custom panel function
xyplot(y ~ x | f, panel = function(x, y, ...) {
 panel.xyplot(x, y, ...) ## First call default panel function
 panel.lmline(x, y, col = 2) ## Overlay a simple linear regression line
})

set.seed(723645)                                   # Create example data
data <- data.frame(x = rnorm(500),
                   y = rnorm(500),
                   group = c(rep("A", 250),
                             rep("B", 250)))
head(data)                                         # Head of example data
##            x           y group
## 1 -2.4512682  1.22588856     A
## 2 -1.0782307 -0.22679003     A
## 3  0.1720944  0.05254144     A
## 4  0.4277141  2.04637615     A
## 5  0.1649821 -0.49608600     A
## 6 -1.0664125 -0.94850249     A
plat1 <- xyplot(y ~ x, data[data$group == "A", ])  # Create plots
plat2 <- xyplot(y ~ x, data[data$group == "B", ])

Including Plots

You can also embed plots, for example:

#install.packages("gridExtra")                      # Install gridExtra package
library("gridExtra")                               # Load gridExtra package
grid.arrange(plat1, plat2, ncol = 2)               # Apply grid.arrange

grid.arrange(plat1, plat2,plat1, plat2,plat1, plat2, plat1, plat2, ncol = 4, nrow=2)

Read the docs