iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 18
0
Big Data

R語言與機器學習見面會系列 第 18

Day18 R語言箱型圖(Box)

  • 分享至 

  • twitterImage
  •  

記得第一次聽到箱形圖,不知道為何,就是會和藏寶圖聯想在一塊。
箱形圖(Box)也稱為盒鬚圖或箱線圖,用一個方形的箱子顯示數據的分佈情形,通常在箱子外的資料會被稱為離群值,可以表達數據分散的情況。

箱形圖的中心線上下及箱型上下邊界可以表達數據中的最大值、最小值、中位數、Q3及Q1四分位數。

R語言中,我們可以用ggpolt2套件中的函數geom_boxplot()

http://docs.ggplot2.org/0.9.3.1/geom_boxplot.html

我們在資料夾MyR新增一支Day18.R

http://ithelp.ithome.com.tw/upload/images/20161218/20103434YrfkBrXfuG.png

箱形圖初次見面

這邊我們使用R內建的資料集ToothGrowth,他是一個實驗維生素C劑量和牙齒生長長度關係的數據紀錄。

在Day18.R中輸入程式碼

#使用長度先畫箱形圖 
ggplot(ToothGrowth, aes(x = 0, y = len)) + geom_boxplot() 

執行結果
http://ithelp.ithome.com.tw/upload/images/20161218/20103434nJPpQEvxx1.png

  • 箱形的上方是Q3,下方是Q1
  • 箱形高度就是ICQ= Q3-Q1
  • 中間的線是中位數

但沒辦法看出給藥方式的差異。

分類

試試看將X軸改為Supp(給藥方式)

在Day18.R中輸入程式碼

#X軸改用兩種給藥方式(柳橙汁(OG)或維生素C(VC)) 
ggplot(ToothGrowth, aes(x = supp, y = len)) + geom_boxplot(width = .5)  

執行結果

http://ithelp.ithome.com.tw/upload/images/20161218/20103434C1Fl2L77dt.png

缺口效果


在Day18.R中輸入程式碼

#加上缺口效果和平均數的點 
ggplot(ToothGrowth, aes(x = supp, y = len)) + geom_boxplot(width = .5, notch = TRUE) + 
stat_summary(fun.y = "mean", geom = "point", shape = 23, size = 3, fill = "blue") 

執行結果

http://ithelp.ithome.com.tw/upload/images/20161218/201034349KWf2Dn3Vi.png

結合點看分佈


在Day18.R中輸入程式碼

#X加上點圖(DotPlot) 
ggplot(ToothGrowth, aes(x = supp, y = len)) + geom_boxplot(width = .5) + 
geom_dotplot(binaxis = "y", binwidth = .5, stackdir = "center") 

http://ithelp.ithome.com.tw/upload/images/20161218/201034343qgMTouR7a.png

加上註釋


在Day18.R中輸入程式碼

#加上註釋(Text Annotations) 
ggplot(ToothGrowth, aes(x = supp, y = len)) + geom_boxplot(width = .5) + 
geom_dotplot(binaxis = "y", binwidth = .5, stackdir = "center") + 
annotate("text", x = 1, y = 36, label = "喝柳橙汁") + 
annotate("text", x = 2, y = 36, label = "吃維他命C") 

http://ithelp.ithome.com.tw/upload/images/20161218/20103434GSMt9hr5Kn.png

上色


在Day18.R中輸入程式碼

#boxplot再加上顏色(default color)  
ggplot(ToothGrowth, aes(x = supp, y = len, fill = supp)) + geom_boxplot(width = .5) + 
geom_dotplot(binaxis = "y", binwidth = .5, stackdir = "center") +  
annotate("text", x = 1, y = 36, label = "喝柳橙汁") + 
annotate("text", x = 2, y = 36, label = "吃維他命C") 

http://ithelp.ithome.com.tw/upload/images/20161218/20103434NieYAnVM4c.png

今天是台北馬拉松(taipei marathon)要跑初馬(初次馬拉松),就像鐵人賽第一次參加,希望自己可以堅持到最後,可以平順完成比賽。

http://ithelp.ithome.com.tw/upload/images/20161218/20103434ZfQpldBXM9.jpg

2016.12.17攝於象山,台北

參考

http://docs.ggplot2.org/0.9.3.1/geom_boxplot.html
R Graphics cookbook

出發!


上一篇
Day17 R語言長條圖(Bar Graph)及R Markdown執行
下一篇
Day19 R語言小提琴圖(Violin Plot)
系列文
R語言與機器學習見面會30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言