ggplot2 繪圖套件

(一) ggplot2說明

Step1. 先以ggplot(train , aes(x=Survived))繪製出網布,再畫上geom_開頭的圖層。舉geom_bar為.例,參數有 : mapping, data, stat, position,一般來說,不會在geom_開頭函數指定data,輸入geom_bar()直接透過ggplot知道正在依照train繪圖。

Step2. 透過geom_bar的mapping參數知道畫的是Survived,而mapping參數都是用aes(Aesthetic美學的)建立相對應的物件,語法類似aes(x=Survived),mapping(映射)內的東西為data欄位
#注意,Survived不須加上雙引號

ex. ggplot( train, aes( x=Survived)) + geom_bar( aes( fill=Sex), position=" stack ") + ggtitle(...) + xlab(...) + ylab(...) 
      fill=Sex #不同類別上不同顏色
      position="stack"(預設堆疊) / "dodge(分開疊)" / "fill(百分比)"
      stat="identity" 表示y軸不再用count

ex. ggplot( combine[1:891,],  aes( x = FamilySize)) + geom_bar( aes( fill = factor( Survived)), stat= 'count', position = 'dodge') 





Q. Why無法改成 ggplot(train, aes(x=Sex))+geom_bar(aes(fill=Survived))  
A : Sex資料型態須改成factor

ggplotly加入互動性

install.packages("plotly")
library(plotly)

static_gg <- ggplot(mpg, aes(x=class))+geom_bar(aes(fill=drv))
ggplotly(static_gg)

(二)常用搞混幾何圖 : histogram(直方) vs bar(長條)

直方 : x 軸為連續變數
           可用「2的幂次方法則」判斷組數
長條 : 通常比較2個或2個以上價值得單變量


(三)圖行化表示多變數的缺失值位置

##Build function
plot_missing <- function(input){
    temp_dt <- data.frame(ifelse(is.na(input),0,1))
    temp_dt <- temp_dt[ ,order(colSums(temp_dt))]
    plotxy_name <- expand.grid(list( 1:nrow(temp_dt),colnames(temp_dt) ))
    plotxy_name$m <- as.vector(as.matrix(temp_dt))
    plotxy_name <- data.frame(x=unlist(plotxy_name$Var1), y=unlist(plotxy_name$Var2),          
    m=unlist(plotxy_name$m))
    ggplot(plotxy_name)+geom_tile(aes(x=x, y=y, fill=as.factor(m)))+scale_fill_manual(values =     
    c("white","black"),name="Missing\n(0:Yes,1:No)")+theme_light()
}
#expand.grid先做出一格一格的畫布
#geom_tile上色( tile:磚瓦 )

##Function call
plot_missing(train[,colSums(is.na(train))>0],with=FALSE)
#若無 with=FALSE 顯示 error : nrow(temp_dt) : argument of length 0


##Plot

(四)ggplot圖上畫水平線

ggplot(combine, aes(x=Embarked, y=Fare))+geom_boxplot(aes(fill=as.factor(Pclass)))+geom_hline(aes(yintercept=80, color="red"))






































































留言

這個網誌中的熱門文章

填補遺漏值(Missing Value)方法

Titanic資料分析#2

分類演算法