# 周次:w13
# 任務:應用(資料框處理與繪圖)
# 姓名:廖呈祐
# 日期:2021年4月28日
### 資料框處理
# 請至台灣傳播資料庫下載「2019年調查」的sav檔
# 網址:https://www.crctaiwan.nctu.edu.tw/AnnualSurvey.asp
## 1. 將輸入的sav檔案命名為tcs2019
#install.packages("sjlabelled")
library(sjlabelled)
tcs2019 <- read_spss("tcs2019.sav") 

# ## 2. 檢視資料框的各種函數
# # 列數
# nrow(tcs2019)
# # 檢視資料框內容
# View(tcs2019)
# # 前六行
# head(tcs2019)
# # 後六行
# tail(tcs2019)
# # 欄位名稱或變數名稱
# names(tcs2019)
# # 另一種寫法
# colnames(tcs2019)
# # 得知每個變數的描述性統計量
# summary(tcs2019)
# # 得知資料框複合式的資訊
# # (含資料結構種類、觀察值個數、變數個數、前幾筆觀察值資訊等)
# str(tcs2019)
# ## 欄數
# ncol(tcs2019)
# ## 維度
# dim(tcs2019)
# ## 列的索引值
# row.names(tcs2019)
# 
# # 當資料較大時,建議使用sjPlot套件
#library(sjPlot)
#view_df(tcs2019,
#         file="tcs2019tab.html",  # 結果直接另存新檔
#         show.na = T, # 顯示未重新編碼前的無效值個數
#         show.frq = T, # 顯示次數
#         show.prc = T, # 顯示百分比
#         encoding = "big5"
# )
### 3. 應用實作
# 偵測與處理,讓65+熟齡族告別假新聞危害 
# http://www.crctaiwan.nctu.edu.tw/epaper/%E7%AC%AC202%E6%9C%9F20210409.htm
# RQ1:遇到假新聞的經驗,是否有年齡層的差異存在呢?
# RQ2:對假新聞的感受,是否有年齡層的差異存在呢?
# RQ3:對假新聞的確認與處理方式等,是否有年齡層的差異存在呢?

# (1)確認欲分析的變數
# 年齡 ra2
# 是否有遇到過假新聞? i12.1
# 對假新聞的感受:
# 普遍性 i7a
# 嚴重性 i7b
# 受影響的可能性 i7c
# 確認你接觸到的新聞是不是假新聞? i11.1-i11.8
# 遇到假新聞,你會如何處理? i12.2.1-i12.2.8

# (2)變數整理
# 年齡「變數重新分類」為4類:18-35,36-49,50-64,65UP
# 備註:break的值(x,y,z)是指: group1 >x & <=y; group2 >y & <=z
tcs2019$agegroup <- cut(tcs2019$ra2, breaks=c(17,35,49,64, Inf),labels=c("18至35歲","36到49歲","50歲到64歲","65歲以上"))
# 檢視各類別有多少人?
#table(tcs2019$agegroup)
# 另一種方法:製作次數分配表
# install.packages("sjmisc")
#library(sjmisc)
#frq(tcs2019$agegroup, encoding="big-5", out="v")
### (3)回答RQ
## RQ1:遇到假新聞的經驗,是否有年齡層的差異存在呢?
## 製表
#library(sjPlot)
#sjt.xtab(tcs2019$agegroup, tcs2019$i12.1, encoding="utf-8")
#sjt.xtab(tcs2019$i12.1,tcs2019$agegroup, encoding="utf-8",show.cell.prc = T,show.row.prc = T,show.col.prc = T)
#xy軸調換
## 製圖
# 1. 變數處理
# (1) 將要繪製的變數變成類別變數或先進行排序
#class() 查詢變數類別的工具
tcs2019$i12.1 <- as.factor(tcs2019$i12.1)
#tcs2019$agegroup <- factor(tcs2019$agegroup, ordered = TRUE,
#                       levels = c("65歲以上", "50至64歲","36至49歲","18至35歲"))

# 2. 安裝並載入 ggplot2
library(ggplot2)
# 參考 R for Data Science書籍: https://r4ds.had.co.nz/index.html
# 參考ggplot2書籍: https://ggplot2-book.org/index.html
# https://blog.gtwang.org/r/ggplot2-tutorial-layer-by-layer-plotting/3/
# https://rpubs.com/chiahung_tsai/lecture05012018
# https://yijutseng.github.io/DataScienceRBook/vis.html
# https://bookdown.org/jefflinmd38/r4biost/dataviz.html
#install.packages("ggplot2")
# 載入 ggplot2
# 解決Rstudio cloud圖形中文顯示問題
#install.packages("showtext")
library(showtext)
## Loading required package: sysfonts
## Loading required package: showtextdb
showtext_auto()

# 3. 以圖層疊加的方式繪圖
# (1) 建立基本圖形(長條圖)
#g1 <- ggplot(tcs2019, 
#            aes(x=agegroup, fill=i12.1))+geom_bar() #+geom_bar()預設為+geom_bar(position="stack")
# g1
# # 或者調整為並排的圖形
# g1 <- ggplot(tcs2019, 
#              aes(agegroup, fill=i12.1))+
#   geom_bar(position = "dodge")
# g1
# 
# # 或者調整為變成標準化的圖形
# g1 <- ggplot(tcs2019, 
#              aes(agegroup, fill=i12.1))+
#   geom_bar(position="fill")
# g1
# 
# # (2) 自訂標題、x軸與y軸名稱
# g2 <- g1+labs(title = "台灣民眾各年齡層遇到假新聞的經驗比較",
#               x="各年齡層",y="次數/比例",
#               subtitle="65+熟齡族與其他年齡有差異?",
#               caption="資料來源:台灣傳播調查資料庫")
# g2
# 
# # 調整y軸(是連續型的變數)的刻度
# g2.1 <- g2+scale_y_continuous(breaks = c(0,0.25,0.5,0.75,1) ,labels =c("0%","25%","50%","75%","100%"))
# g2.1
# 
# # 若是類別型的刻度
# g2.2 <- g2+scale_x_discrete("年齡分組",labels = c("18至35歲" = "18-35","36至49歲" = "36-49",
#                                               "50至64歲" = "50-64", "65歲以上" = "65 up"))
# g2.2 
# 
# # (3) 設定背景
# # 隱藏格線 
# g3.1 <- g2+theme(panel.grid.major = element_blank(),
#                  panel.grid.minor = element_blank()) 
# g3.1
# 
# # 背景空白
# g3.2 <- g2+theme(panel.background = element_blank()) 
# g3.2
# 
# # 標題置中
# g3.3 <- g3.2+theme(plot.title = element_text(hjust = 0.5))
# g3.3
# 
# # 調整y軸標題的方向
# g3.4 <- g3.3+theme(axis.title.y = element_text(vjust = 0.5, hjust = 0.5, angle = 0))
# g3.4
# 
# # 內建的主題效果
# # theme_bw()
# # theme_dark() 
# # theme_classic()
# # theme_gray()
# # theme_linedraw()
# # theme_light()
# # theme_minimal()
# # theme_test()
# # theme_void()
# g3.5 <- g2+theme_classic()
# g3.5
# 
# # (4) 設定圖例
# g4 <- g3.4+scale_fill_discrete(name="接觸經驗",
#                                breaks=c("1", "2", "3"),
#                                labels=c("有遇到過假新聞", "從未遇過假新聞", "不知道是否遇過假新聞"))
# g4
# 
# # (5) 調整圖形為水平方向
# g5 <- g4+coord_flip() 
# g5
# 
# # (6) 在圖上加上次數/比例的文字
# # a. 若想於堆疊的長條圖上繪製文字 #geom_bar(position="stack")
# g1 <- ggplot(tcs2019, 
#              aes(x=agegroup, fill=i12.1))+geom_bar() #+geom_bar()預設為+geom_bar(position="stack")
# g1+geom_text(stat="count",aes(label=..count..),
#              position = position_stack(vjust = 1),
#              size = 3, color = "yellow")
# 
# # b. 若想於並排的長條圖上繪製文字 #geom_bar(position = "dodge")
# g1 <- ggplot(tcs2019, 
#              aes(agegroup, fill=i12.1))+geom_bar(position = "dodge")
# g1+geom_text(stat="count",aes(label=..count..),
#              position = position_dodge(width = 1),
#              size = 3, color = "blue")
# g1 <- ggplot(tcs2019, 
#              aes(agegroup, fill=i12.1))+geom_bar(position = "dodge")
# g1+geom_text(stat="count",aes(label=..count..),
#              position = position_dodge(width = 1),
#              size = 3, color = "blue")
# 
# # c. 若想於標準化的長條圖上繪製文字,建議重建專用的資料集
# # 參考https://ithelp.ithome.com.tw/articles/10209002
# # install.packages("plyr")
# library(plyr)
# ess2 = ddply(tcs2019,.(agegroup),function(.){
#   res = prop.table(table(factor(.$i12.1)))
#   res2 = table(factor(.$i12.1))
#   data.frame(lab=names(res), y=c(res),yy =c(res2))
# })
# detach("package:plyr", unload=TRUE)
# # 繪製基本圖 #其他需求可自行調整
# ggplot(ess2,aes(x = agegroup,y=y,fill = lab))+
#   geom_bar(stat = "identity")+
#   geom_text(mapping = aes(label = sprintf("%.2f%%",y*100)),
#             size = 2, colour = 'black', vjust = 2, hjust = .5, position = position_stack())
# 
# # (7) 依照變數分類,各組繪製一張直方圖(但僅能應用於基本的長條圖類型)
# g1 <- ggplot(tcs2019, 
#              aes(x=i12.1, fill=agegroup))+geom_bar() #+geom_bar()預設為+geom_bar(position="stack")
# g1+facet_grid(.~agegroup)
# # 變數可互換位置,檢視自己想要強調哪個變項
# g1 <- ggplot(tcs2019, 
#              aes(x=agegroup, fill=i12.1))+
#   geom_bar()
# g1+facet_grid(.~i12.1)
# 
# # (調整顏色(若原本已有設定顏色,此功能將會取代原本的顏色設定)
# # 可運用色票網站https://color.adobe.com/zh/explore
# g1 <- ggplot(tcs2019, 
#              aes(x=agegroup, fill=i12.1))+geom_bar() #+geom_bar()預設為+geom_bar(position="stack")
# g1+scale_fill_manual(values=c("#F7908B", "#72B7F7", "#3E76AB"))
# # 可運用內建顏色
# colors()
# g1 <- ggplot(tcs2019, 
#              aes(x=agegroup, fill=i12.1))+geom_bar() #+geom_bar()預設為+geom_bar(position="stack")
# g1+scale_fill_manual(values=c("lightskyblue1", "rosybrown2", "steelblue1"))
# 

## 請依據上述參數,自行繪製「台灣民眾各年齡層遇到假新聞的經驗比較」一圖
## 基本要求:
# 1. 要有主標題、x,y軸名稱及刻度名稱
# 2. 要有圖例說明
# 3. 圖上須注記作者姓名及資料來源

# 1. 堆疊的長條圖
ggplot(tcs2019, aes(x=agegroup, fill=i12.1))+ geom_bar()+
  labs(title = "台灣民眾各年齡層遇到假新聞的經驗比較",
       x="各年齡層",y="次數",
       caption="LCY製 資料來源:台灣傳播調查資料庫")+
  theme(axis.title.y = element_text(vjust = 0.5, hjust = 0.5,
                                    angle = 0))+
  geom_text(stat="count",aes(label=..count..),
            position = position_dodge(width = 0),
            size = 2, color = "black")+  
  scale_fill_manual(name="接觸經驗",values=c("1"="yellow", "2"="rosybrown2", "3"="steelblue1"),
                    labels=c("有遇到過假新聞", "從未遇過假新聞", "不知道是否遇過假新聞"))

# 2. 標準化的長條圖
ggplot(tcs2019,  aes(agegroup, fill=i12.1))+
  labs(title = "台灣民眾各年齡層遇到假新聞的經驗比較",
       x="各年齡層",y="比例",
       caption="LCY製 資料來源:台灣傳播調查資料庫")+
  geom_bar(position="fill")+
  scale_y_continuous(breaks = c(0,0.25,0.5,0.75,1) ,
                     labels =c("0%","25%","50%","75%","100%"))+
  theme(axis.title.y = element_text(vjust = 0.5, hjust = 0.5,
                                    angle = 0))+
  scale_fill_manual(name="接觸經驗",values=c("1"="brown", "2"="rosybrown2", "3"="steelblue1"),
                    labels=c("有遇到過假新聞", "從未遇過假新聞", "不知道是否遇過假新聞"))

# 3. 並排的長條圖
ggplot(tcs2019, 
       aes(agegroup, fill=i12.1))+
  labs(title = "台灣民眾各年齡層遇到假新聞的經驗比較",
       x="各年齡層",y="次數",
       caption="LCY製 資料來源:台灣傳播調查資料庫" )+
  geom_bar(position = "dodge")+
  theme(axis.title.y = element_text(vjust = 0.5, hjust = 0.5,
                                    angle = 0))+
  scale_fill_manual(name="接觸經驗",values=c("1"="yellow", "2"="rosybrown2", "3"="steelblue1"),
                    labels=c("有遇到過假新聞", "從未遇過假新聞", "不知道是否遇過假新聞"))

# 4. 不同年齡層各繪製一張直方圖
ggplot(tcs2019, 
       aes(x=i12.1, fill=agegroup))+geom_bar()+
  theme(axis.title.y = element_text(vjust = 0.5, hjust = 0.5,
                                    angle = 0))+
  scale_x_discrete("是否遇見假新聞",labels = c("1"="有","2"="沒有","3"="不知道"))+
  facet_grid(.~agegroup)+labs(title = "台灣民眾各年齡層遇到假新聞的經驗比較",
                              y="次數",caption="LCY製 資料來源:台灣傳播調查資料庫")

# 1. 類別變數:區分有序(如月份、年齡層)、無序(如使用社群媒體種類)
# 2. 連續變數:區分為離散(如年齡)、非離散型(如身高、體重)
# cut函數可將離散型連續變數轉換為有序的類別變數