##先調資料庫datasets、啟用語法lattice、使用資料VADeaths
library(datasets)
library(lattice)
data(VADeaths)
##定義VADeaths
class(VADeaths)
## [1] "matrix"
##dotplot擁有的s內容
methods("dotplot")
## [1] dotplot.array* dotplot.default* dotplot.formula* dotplot.matrix*
## [5] dotplot.numeric* dotplot.table*
## see '?methods' for accessing help and source code
##使用ggplot2畫點圖,VADeaths為Condition加上內部組別比較
dotplot(VADeaths, groups=FALSE)

##dotplot畫圖,指定大小
dotplot(VADeaths, groups=FALSE,
layout=c(1, 4),
aspect=0.7,
origin=0,
type=c("p", "h"),
main="Death Rates in Virginia - 1940",
xlab="Rate (per 1000)")

##auto.key=TRUE將可以創建一個擺放在圖形上方的、初步的圖例符號,將所修改以列表形式添加到自動圖例符號。
dotplot(VADeaths, type="o",
auto.key=list(lines=TRUE, space="right"),
main="Death Rates in Virginia - 1940",
xlab="Rate (per 1000)")

##barplot()函數來畫長條圖
barchart(VADeaths, groups=FALSE,
layout=c(1, 4),
aspect=0.7,
reference=FALSE,
main="Death Rates in Virginia - 1940",
xlab="Rate (per 100)")

##打開latticeExtra中的資料postdoc
data(postdoc, package="latticeExtra")
##barplot()來畫條長條圖,prop.table計算表格內的百分比
barchart(prop.table(postdoc, margin=1),
xlab="Proportion",
auto.key=list(adj=1))

##dotplot()以點圖來畫資料prop.table表格百分比,par.strip.text控制外觀
dotplot(prop.table(postdoc, margin=1),
groups=FALSE,
xlab="Proportion",
par.strip.text=list(abbreviate=TRUE, minlength=10))

##index.cond列出順序,layout()組合多組圖形,aspect控制長寬比,prepanel預先處理數據,panel指定實際畫圖
dotplot(prop.table(postdoc, margin=1),
groups=FALSE,
index.cond=function(x, y) median(x),
xlab="Proportion",
layout=c(1, 5),
aspect=0.6,
scales=list(y=list(relation="free", rot=0)),
prepanel=function(x, y) {
list(ylim=levels(reorder(y, x)))
},
panel=function(x, y, ...) {
panel.dotplot(x, reorder(y, x), ...)
})

##使用mlmRev中的資料Chem97
data(Chem97, package="mlmRev")
##xtabs根據多個項度製成表格
gcsescore.tab <- xtabs(~ gcsescore + gender, Chem97)
##as.data.frame儲存成矩陣資料格式
gcsescore.df <- as.data.frame(gcsescore.tab)
##as.numeric將gcsescore儲存成數字形式,as.character轉換成文字的形式
gcsescore.df$gcsescore <- as.numeric(as.character(gcsescore.df$gcsescore))
##使用xyplot語法畫lattice散佈圖,指定x 與y 軸的資料,y值=Freq,X值gcsescore,Z值=gender
xyplot(Freq ~ gcsescore | gender,
data = gcsescore.df,
type="h",
layout=c(1, 2),
xlab="Average GCSE Score")

##xtabs根據多個項度製成表格
score.tab <- xtabs(~score + gender, Chem97)
##as.data.frame儲存成矩陣資料格式
score.df <- as.data.frame(score.tab)
##製作barchart()長條圖
barchart(Freq ~ score | gender, score.df, origin=0)

## The End