#
##seq()快速產生向量函數
x <- seq(-pi*2, 2*pi, .05)
##dnorm表現常態分配在 x 的機率密度函數值
z <- dnorm(x)
##T分佈中,x 所對應的密度
y <- dt(x, df=100)
##以X和Z畫圖, bty可以取6種字元,不同字元代表6種邊框。
plot(x, z, type="l", bty="L", xlab="Standard unit", ylab="Density")
##面積函數畫出 polygon() 可以用來繪製圖形,rev()將整個向量倒過來排,col設定顏色淺藍
polygon(c(x, rev(x)), c(y, rev(z)), col='aliceblue')
##lines加上直線
lines(x, y, col='cadetblue')

###df值越高,T分配越集中,X和Z值越接近,淺藍面積越少。

#
x <- seq(-pi*2, 2*pi, .05)
z <- dnorm(x)
y <- dt(x, df=3)
plot(x, z, type="l", bty="L", xlab="Standard unit", ylab="Density")
polygon(c(x, rev(x)), c(y, rev(z)), col='aliceblue')
lines(x, y, col='cadetblue')

###
##讀檔txt
dta <- read.table("C:/tmp/cigarettes.txt", header=T , stringsAsFactor=F, fill=T )
head(dta)
##     Country consumption death
## 1 Australia         480   180
## 2    Canada         500   150
## 3   Denmark         380   170
## 4   Finland        1100   350
## 5        UK        1100   460
## 6   Iceland         230    60
str(dta)
## 'data.frame':    11 obs. of  3 variables:
##  $ Country    : chr  "Australia" "Canada" "Denmark" "Finland" ...
##  $ consumption: int  480 500 380 1100 1100 230 490 250 300 510 ...
##  $ death      : int  180 150 170 350 460 60 240 90 110 250 ...
##畫圖X軸、Y軸
with(dta, plot(consumption, death, 
               xlab="consumption (per capita year)", 
               ylab="death (per million)", 
               pch=1, 
               bg='lavender',
               ylim = NULL,
               main="Lung Cancer & Cigarettes consumption"))
m0 <- lm(consumption ~ death, data=dta,lty=2)
## Warning: In lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
##  extra argument 'lty' will be disregarded
##Abline虛線點連直線(輔助線)
abline(m0)
##使用text()函数在圖添加文字
text(dta$consumption, dta$death, dta$Country)
##Segments呈現到回歸線的距離
with(dta, segments(consumption, 
                   death, 
                   consumption, 
                   predict(m0), 
                   lty=3))