xyplot - Example 1
#install.packages("lattice")
library(lattice)
state = data.frame(state.x77, region = state.region)
xyplot(Life.Exp ~ Income | region, data = state, layout = c(4,1))
xyplot - Example 2
library(lattice)
library(datasets)
xyplot(Ozone ~ Wind, data = airquality)
xyplot - Example 3
library(lattice)
library(datasets)
airquality1 = transform(airquality, Month = factor(Month))
str(airquality)
## 'data.frame': 153 obs. of 6 variables:
## $ Ozone : int 41 36 12 18 NA 28 23 19 8 NA ...
## $ Solar.R: int 190 118 149 313 NA NA 299 99 19 194 ...
## $ Wind : num 7.4 8 12.6 11.5 14.3 14.9 8.6 13.8 20.1 8.6 ...
## $ Temp : int 67 72 74 62 56 66 65 59 61 69 ...
## $ Month : int 5 5 5 5 5 5 5 5 5 5 ...
## $ Day : int 1 2 3 4 5 6 7 8 9 10 ...
str(airquality1)
## 'data.frame': 153 obs. of 6 variables:
## $ Ozone : int 41 36 12 18 NA 28 23 19 8 NA ...
## $ Solar.R: int 190 118 149 313 NA NA 299 99 19 194 ...
## $ Wind : num 7.4 8 12.6 11.5 14.3 14.9 8.6 13.8 20.1 8.6 ...
## $ Temp : int 67 72 74 62 56 66 65 59 61 69 ...
## $ Month : Factor w/ 5 levels "5","6","7","8",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ Day : int 1 2 3 4 5 6 7 8 9 10 ...
xyplot(Ozone ~ Wind | Month, data = airquality, layout=c(5,1))
Lattice Behaviour
p = xyplot(Ozone ~ Wind, data=airquality) ## Nothing happens
print(p) ## Plot appears
xyplot(Ozone ~ Wind, data=airquality) ## Autoprinting
Lattice Panel Functions
set.seed(10)
x = rnorm(100)
f = rep(0:1, each = 50)
y = x + f - f * x + rnorm(100, sd=0.5)
str(f)
## int [1:100] 0 0 0 0 0 0 0 0 0 0 ...
f = factor(f, labels = c("Group 1","Group 2"))
str(f)
## Factor w/ 2 levels "Group 1","Group 2": 1 1 1 1 1 1 1 1 1 1 ...
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 functino for 'xyplot'
panel.abline(h=median(y), lty=2) # Add a horizontal line at the median
}
)
Lattice panel fucntinos: Regression Line
xyplot(y ~ x | f, panel=function(x,y,...){
panel.xyplot(x,y,...) # First call the default panel functino for 'xyplot'
panel.lmline(x,y,col=2) # Add a simple regression linbe
}
)