1. 繪圖函數:
- lattice 包:
· xyplot / bwplot / histogram / stripplot / dotplot / splom / levelplot / contourplot
· 格式:xyplot ( y ~ x | f * g , data )
· panel 函數,用於控制每個面板內的繪圖
- grid 包:
· 實現了獨立於base的繪圖系統
· lattice包是基於grid創建的;很少直接從grid包調用函數
2. Lattice 與 Base 的重要區別
- Base 繪圖函數直接在圖形設備上繪圖
- 而Lattice 繪圖函數返回 trellis 類對象
· 打印函數真正執行了在設備上繪圖
· 命令執行時,trellis 類對象會被自動打印,所以看起來就像是 lattice 函數直接完成了繪圖
3. 實踐
- 安裝 lattice 包:install.packages("lattice")
- 查詢幫助文檔:如 ?xyplot
library(lattice) # 引入lattice包 xyplot(Temp~Ozone, data=airquality) # 考察Temp和Ozone之間的關系 airquality$Month <- factor(airquality$Month) # Month變量轉換成factor,即分類變量 xyplot(Temp~Ozone | Month, data=airquality, layout=c(5,1)) # Temp和Ozone 與月份之間的關系(lattice體現交互作用) q <- xyplot(Temp~Wind, data=airquality) # xyplot存到變量里,生成類對象 print(q) # 打印類對象,若xyplot不存入變量,則會直接打印出來 set.seed(1) # 設置種子點,意義在於每次產生的隨機數是一樣的(使用隨機數時切記使用種子點) x <- rnorm(100) # 從變准正態分布中抽取100個隨機數,賦值給x f <- rep(0:1, each=50) # f變量只包含0和1這兩個值,每個值出現50次,所以f變量內有100個數 y <- x + f - f*x + rnorm(100, sd=0.5) # 讓x與y之間的關系與f變量有交互 f <- factor(f, labels=c("Group1","Group2")) # f變量轉換成factor,即分類變量 xyplot(y~x | f, layout=c(2,1)) # x和y 與f之間的關系 xyplot(y~x | f, panel=function(x, y){ panel.xyplot(x,y) panel.abline(v=mean(x), h=mean(y), lty=2) panel.lmline(x,y,col="red") }) # abline:添加x平均直線,添加y平均直線 # lmline:擬合線性模型