1.分組散點圖
①xyplot()函數
> library(lattice) > xyplot(mpg~disp, #定義Y~X軸 + data=mtcars, + groups=cyl, #定義分組 + auto.key=list(corner=c(1,1))) #設置圖例

②qplot()函數
> library(ggplot2) #加載包 > qplot(disp,mpg,data=mtcars, + col= as.factor(cyl)) #用顏色分組 > qplot(disp,mpg,data=mtcars, + shape=as.factor(cyl)) #用形狀分組 > qplot(disp,mpg,data=mtcars, + size=as.factor(cyl)) #用大小分組



2.添加標識點 #text()函數
> health<-read.csv("HealthExpenditure.csv",header=TRUE)
> plot(health$Expenditure,health$Life_Expectancy,type="n") #定義X軸,Y軸,以無散點形式畫圖
> text(health$Expenditure,health$Life_Expectancy,health$Country) #以坐標添加城市名為標識點

3.相關系數散點圖
> panel.cor <- function(x, y, ...)
+ {
+ par(usr = c(0, 1, 0, 1)) #自定義每個坐標系范圍
+ txt <- as.character(format(cor(x, #cor計算相關系數,as.character轉換為字符串
+ y), digits=2)) #digits=2保留兩位小數
+ text(0.5, 0.5, txt, cex = 6* #以(0.5,0.5)的坐標標識相關系數
+ abs(cor(x, y))) #數字大小為相關系數的六倍
+ }
> pairs(iris[1:4], #以iris數據集的1到4列兩兩組合畫散點圖
+ upper.panel=panel.cor) #右上方的三角形區域畫相關系數代替散點圖

4.誤差條 #arrows()函數
> plot(mpg~disp,data=mtcars) > arrows(x0=mtcars$disp, #設置起始點 + y0=mtcars$mpg*0.95, #設置向下的終點 + x1=mtcars$disp, + y1=mtcars$mpg*1.05, #設置向上的終點 + angle=90, #設置角度 + code=3, #設置樣式 + length=0.04, #設置長度 + lwd=0.4) #設置寬度 > arrows(x0=mtcars$disp*0.95, #設置向左的終點 + y0=mtcars$mpg, #設置起始點 + x1=mtcars$disp*1.05, + y1=mtcars$mpg, + angle=90, + code=3, + length=0.04, + lwd=0.4)

5.密集散點圖 #jitter()函數:給向量加上少許噪音
> x <- rbinom(1000, 10, 0.25) #隨機生成1000個均值為10*0.25=2.5的數 > y <- rbinom(1000, 10, 0.25) > plot(x,y) > plot(jitter(x), jitter(y))

6.三維散點圖 #scatterplot3d()函數
> library(scatterplot3d) > scatterplot3d(x=mtcars$wt, + y=mtcars$disp, + z=mtcars$mpg)

> scatterplot3d(mtcars$wt,mtcars$disp,mtcars$mpg, + pch=16, #實心散點 + highlight.3d=TRUE, #設置漸變顏色 + angle=20, #X和Y軸的夾角 + xlab="Weight", + ylab="Displacement", + zlab="Fuel Economy (mpg)", + type="h", #畫散點垂直線 + main="Relationships between car specifications")

7.QQ圖(檢驗數據是否服從正態分布)
> qqnorm(mtcars$mpg) #畫散點 > qqline(mtcars$mpg) #畫線(如果為一條直線,則數據服從正態分布)

8.密度表示 #rug()函數
> metals<-read.csv("metals.csv")
> plot(Ba~Cu,data=metals,xlim=c(0,100)) #畫散點圖
> rug(metals$Cu) #密度表示(默認畫在X軸方向)
> rug(metals$Ba,
+ side=2, #在Y軸方向表示
+ col="red",
+ ticksize=0.02) #設置長度

9.霧化散點圖 #smoothScatter()函數
> n <- 10000 > x <- matrix(rnorm(n), ncol=2) > y <- matrix(rnorm(n, mean=3,sd=1.5), ncol=2) > smoothScatter(x,y)

