GGally與pairs相關關係圖_史上最全(一)

2021-02-24 表哥有話講

作者:李譽輝  

四川大學在讀研究生

簡介
對於多個變量之間的相關關係,常常使用相關關係圖來可視化,R自帶有pairs()函數,
可以畫相關關係圖,但是比較複雜,我們先介紹基於ggplot2的GGally包。
等介紹完,再介紹pairs()函數。

ggmatrix()可以將多個ggplot2繪圖對象,按照矩陣進行排列。

1library(ggplot2)
2data(tips, package = "reshape")
3
4head(tips)
5
6g1 <- ggplot(tips, aes(x = total_bill, fill = sex)) + 
7  geom_density(show.legend = FALSE)
8
9g2 <- ggplot(tips, aes(x = total_bill, fill = sex)) + 
10  geom_histogram(position = position_stack(), show.legend = FALSE) + 
11  facet_grid(rows = vars(time))# 以time變量行分面
12
13g3 <- ggplot(tips, aes(x = total_bill, y = tip, color = sex)) + 
14  geom_point(show.legend = FALSE)
15

1library(ggplot2)
2
3g4 <- ggplot(tips, aes(x = time, y = total_bill, fill = sex)) + 
4  geom_boxplot(show.legend = FALSE)
5
6g5 <- ggplot(tips, aes(x = time, fill = sex)) + 
7  geom_bar(position = position_stack(), show.legend = FALSE)
8
9g6 <- ggplot(tips, aes(x = tip, fill = sex)) + 
10  geom_histogram(position = position_stack(), show.legend = FALSE) + 
11  coord_flip() + 
12  facet_grid(cols = vars(time))
13

1library(ggplot2)
2library(dplyr)
3library(tibble) 
4
5# 第一個圖
6text_1 <- round(cor(tips$total_bill, tips$tip), 3)
7tips_female <- as.tibble(tips) %>% filter(sex == "Female") %>% as.data.frame()
8tips_male <- as.tibble(tips) %>% filter(sex == "Male") %>% as.data.frame()
9text_2 <- round(cor(tips_female$total_bill, tips_female$tip), 3)
10text_3 <- round(cor(tips_male$total_bill, tips_male$tip), 3)
11mytext <- c(text_1, text_2, text_3)
12mytext <- paste0(c("Cor", "Female", "Male"), ":", mytext)
13mytext <- data.frame(text = mytext,
14                     x = 5,
15                     y = c(6, 4, 2),
16                     stringsAsFactors = FALSE)
17
18g7 <- ggplot(data = mytext[-1, ], aes(x = x, y = y, label = text, color = text)) + 
19  geom_text(show.legend = F) + 
20  geom_text(data = mytext[1,], aes(x = x, y = y, label = text), 
21            color = "black") 
22
23rm(text_1, tips_female, tips_male, text_2, text_3, mytext)
24
25# 第2個圖
26g8 <- ggplot(tips, aes(x = time, y = tip, fill = sex)) + 
27  geom_boxplot(show.legend = FALSE) + 
28  coord_flip()
29
30# 第3個圖
31g9 <- ggplot(tips, aes(x = tip, fill = sex)) + 
32  geom_density(show.legend = FALSE)
33

1library(customLayout)
2
3mylay <- lay_new(
4  mat = matrix(1:9, ncol = 3))
5
6plot_list <- list(g1, g2, g3, g4, g5, g6, g7, g8, g9) 
7
8lay_grid(plot_list, mylay) 
9
10rm(g1, g2, g3, g4, g5, g6, g7, g8, g9, mylay)

1library(GGally)
2
3gg_m <- ggmatrix(
4  plots = plot_list, 
5  nrow = 3, ncol = 3, 
6  xAxisLabels = c("Total Bill", "Time of Day", "Tip"),
7  yAxisLabels = c("Total Bill", "Time of Day", "Tip"),
8  byrow = FALSE, 
9  title = "ggmatrix合併圖形"
10)
11
12
13gg_m + theme_bw() 
14
15
16gg_m[1,2]
17
18rm(plot_list, gg_m)

GGally通過添加幾個函數來擴展ggplot2,以降低geom與轉換數據組合的複雜性。
其中一些功能包括配對圖矩陣,散點圖矩陣,平行坐標圖,生存圖,以及繪製網絡的幾個函數。

語法:

1ggpairs(data, mapping = NULL, columns = 1:ncol(data), title = NULL,
2  upper = list(continuous = "cor", combo = "box_no_facet", discrete =
3  "facetbar", na = "na"), lower = list(continuous = "points", combo =
4  "facethist", discrete = "facetbar", na = "na"), diag = list(continuous =
5  "densityDiag", discrete = "barDiag", na = "naDiag"), params = NULL, ...,
6  xlab = NULL, ylab = NULL, axisLabels = c("show", "internal", "none"),
7  columnLabels = colnames(data[columns]), labeller = "label_value",
8  switch = NULL, showStrips = NULL, legend = NULL,
9  cardinality_threshold = 15, progress = NULL,
10  legends = stop("deprecated"))

關鍵參數:

mapping, 表示要疊加到x,y上的aes()映射變量,這裡是全局映射。

column, 表示選擇要繪圖的列,可以用變量索引值指定,也可以用變量名指定。

columnLabels, 指定矩陣列名稱。

title, xlab, ylab, 表示指定標題和坐標軸名稱。

lower,upper,表示指定下三角和上三角的plot類型,列表傳參。

diag,表示指定對角線的plot類型,列表傳參。

axisLabels, 指定變量名稱的顯示位置,默認顯示在外側,
"internal"則顯示在內測,"none"則不顯示。

labeller, 表示指定分面標籤,

switch, 表示指定分面標籤位置,與ggplot2:facet_grid中一致,默認在頂部和右側,
若switch = "x",則顯示在底部和右側,若switch = "y"則顯示在頂部和左側,
若swith = "both"則顯示在底部和左側。

showStrips, 布爾運算決定是否顯示plots的條帶,默認NULL只顯示頂部和右側的條帶。
TRUE則顯示所有的條帶,FALSE則不顯示所有的條帶。

legend, 默認NULL不顯示,可以通過theme(legend.position = "bottom")調整圖例的位置。
有3種指定圖例類型的方式:

長度為2的數字向量,表示給矩陣所在的行和列增加圖例。如c(2,3)表示第2行第3列增加圖例。

長度為1的數字向量,表示根據矩陣的順序,給相應的panel添加圖例,
如legend=3表示給1行第3列增加圖例。

預先使用grab_legend()提取ggplot2對象的圖例,然後指定給legend。

cardinality_threshold, 表示允許因子變量的最大因子水平數量,默認最多15個因子水平。NULL則因子變量不會繪圖。

progress, 表示是否顯示進度條,默認NULL當超過15個plots時顯示進度條,
對繪圖結果沒有任何影響,不需要關注。
TRUE則顯示進度條,FALSE則不顯示進度條,
也可用ggmatrix_progress()生成進度條,然後指定。


plot類型:
通過5個參數控制plot類型:continuous,combo,discret, na, mapping

continuous, 表示如果變量x,y都是連續的,應該是什麼plot。

對於lower和upper參數:
可以是

"point", "smooth","smooth_loess", "density", "cor", "blank"。

對於diag參數: 可以是

"densityDiag", "barDiag", "blankDiag"

combo, 表示如果變量一個連續,一個離散,應該是什麼plot。
只能用於lower和upper不能用於diag
離散變量只能計數,不能映射坐標,所以可能存在坐標翻轉

可以是

"box", "box_no_facet", "dot", 

"dot_no_facet",
"facethist", "facetdensity", 

"denstrip", "blank"

discrete, 表示2個變量都是離散的,應該是什麼plot。

對於upper和lower參數:
可以是:

"facetbar", "ratio", "blank"。

對於diag參數: 可以是"barDiag", "blankDiag"。

na, 表示指定變量為na的情況,

mapping, 表示aes()映射。若指定mapping參數,則疊加到x,y上去。

默認

lower = list(continuous = "point", combo = "facetthist", discrete = "facetbar")

默認

upper = list(continuous = "cor", combo = "box_no_facet", discrete = "box")

默認

diag = list(continuous = "density", discrete = "barDiag")

1library(GGally)
2library(ggplot2)
3
4ggpairs(tips, mapping = aes(color = sex), 
5  columns = c("total_bill", "time", "tip"), 
6  columnLabels = c("Total_Bill(連續變量)", "Time(離散變量)", "Tip(連續變量)"),
7  title = "變量名指定column")
8
9ggpairs(tips, mapping = aes(color = sex), 
10  columns = c(1, 6, 2), 
11  columnLabels = c("Total_Bill(連續變量)", "Time(離散變量)", "Tip(連續變量)"),
12  title = "索引值指定column")


 自定義lower

一個離散變量,lower的discrete參數無效。

1ggpairs(tips, mapping = aes(color = day), 
2  columns = c("total_bill", "time", "tip"), 
3  columnLabels = c("Total_Bill(連續變量)", "Time(離散變量)", "Tip(連續變量)"),
4  lower = list(
5    continuous = "cor",
6    combo = "dot_no_facet" 
7  ),
8  upper = list(
9    continuous = "blank",
10    combo = "blank"
11  ),
12  diag = list(
13    continuous = "blankDiag",
14    discrete = "blankDiag"
15  ),
16  title = "自定義lower\n(lower$continuous = \"cor\", lower$combo = \"dot_no_facet\")"
17)

兩個離散變量,lower的continuous參數無效。

1ggpairs(tips, mapping = aes(color = day), 
2  columns = c("total_bill", "time", "sex"), 
3  columnLabels = c("Total_Bill(連續變量)", "Time(離散變量)", "Sex(離散變量)"),
4  lower = list(
5    combo = "dot_no_facet", 
6    discrete = "blank"
7  ),
8  upper = list(
9    combo = "blank",
10    discrete = "blank"
11  ),
12  diag = list(
13    continuous = "blankDiag",
14    discrete = "blankDiag"
15  ),
16  title = "自定義lower\n(lower$combo = \"dot_no_facet\",lower$discrete = \"blank\" )"
17)

 自定義upper

一個離散變量,upper的discrete參數無效。

1ggpairs(tips, mapping = aes(color = day), 
2  columns = c("total_bill", "time", "tip"), 
3  columnLabels = c("Total_Bill(連續變量)", "Time(離散變量)", "Tip(連續變量)"),
4  upper = list(
5    continuous = "density",
6    combo = "dot_no_facet" 
7  ),
8  lower = list(
9    continuous = "blank",
10    combo = "blank"
11  ),
12  diag = list(
13    continuous = "blankDiag",
14    discrete = "blankDiag"
15  ),
16  title = "自定義upper\n(upper$continuous = \"density\", upper$combo = \"dot_no_facet\")"
17)

兩個離散變量,upper的continuous參數無效。

1ggpairs(tips, mapping = aes(color = day), 
2  columns = c("total_bill", "time", "sex"), 
3  columnLabels = c("Total_Bill(連續變量)", "Time(離散變量)", "Sex(離散變量)"),
4  upper = list(
5    combo = "dot_no_facet", 
6    discrete = "ratio"
7  ),
8  lower = list(
9    combo = "blank",
10    discrete = "blank"
11  ),
12  diag = list(
13    continuous = "blankDiag",
14    discrete = "blankDiag"
15  ),
16  title = "自定義upper\n(lower$combo = \"dot_no_facet\",upper$discrete = \"ratio\" )"
17)

 自定義diag

diag沒有combo參數。

1ggpairs(tips, mapping = aes(color = day), 
2  columns = c("total_bill", "time", "tip"), 
3  columnLabels = c("Total_Bill(連續變量)", "Time(離散變量)", "Tip(連續變量)"),
4  diag  = list(
5    continuous = "barDiag",
6    discrete = "blankDiag" 
7  ),
8  lower = list(
9    continuous = "blank",
10    combo = "blank"
11  ),
12  upper = list(
13    continuous = "blank",
14    combo = "blank"
15  ),
16  title = "自定義diag\n(diag$continuous = \"barDiag\", diag$discrete = \"blankDiag\")"
17)

1ggpairs(tips, mapping = aes(color = day), 
2  columns = c("total_bill", "time", "sex"), 
3  columnLabels = c("Total_Bill(連續變量)", "Time(離散變量)", "Sex(離散變量)"),
4  diag = list(
5    continuous = "barDiag", 
6    discrete = "barDiag"
7  ),
8  lower = list(
9    discrete = "blank",
10    combo = "blank"
11  ),
12  upper = list(
13    discrete = "blank",
14    combo = "blank"
15  ),
16  title = "自定義diag\n(lower$continuous = \"barDiag\",diag$barDiag = \"barDiag\" )"
17)

 mapping參數

1library(ggplot2)
2library(GGally)
3data(tips, package = "reshape")
4
5ggpairs(tips, 
6        columns = c("total_bill", "time", "tip"),
7        columnLabels = c("Total_Bill(連續變量)", "Time(離散變量)", "Tip(連續變量)"),
8        title = "無mapping"
9)

1ggpairs(tips, 
2        columns = c("total_bill", "time", "tip"),
3        columnLabels = c("Total_Bill(連續變量)", "Time(離散變量)", "Tip(連續變量)"),
4        lower = list(mapping = aes(color = time)),
5        title = "自定義lower(lower$mapping = \"time\")" 
6)

1ggpairs(tips, 
2        columns = c("total_bill", "tip", "size"),
3        columnLabels = c("Total_Bill(連續變量)", "Tip(連續變量)", "Size(連續變量)"),
4        lower = list(
5          continuous = "cor", 
6          mapping = aes(color = sex)
7          ),
8        upper = list(
9          continuous = "cor",
10          mapping = aes(color = smoker)
11        ),
12        diag = list(
13          continuous = "barDiag",
14          mapping = aes(color = time)
15        ),
16        title = "自定義lower,upper,diag\n(下三角顏色為sex,上三角顏色為smoker,對角顏色為time)" 
17)

 同時指定lower,upper,diag

2個連續變量,1個離散變量。

1ggpairs(tips, mapping = aes(color = day), 
2        columns = c("total_bill", "tip", "time"),
3        columnLabels = c("Total_Bill(連續變量)", "Tip(連續變量)", "Time(離散變量)"),
4        lower = list(
5          continuous = "cor",
6          combo = "dot_no_facet" 
7        ),
8        upper = list(
9          continuous = "density",
10          combo = "dot_no_facet" 
11        ),
12        diag  = list(
13          continuous = "barDiag",
14          discrete = "blankDiag" 
15        ),
16        title = "自定義lower,upper,diag(兩個連續變量,一個離散變量)" 
17)

1個連續變量,2個離散變量。

1ggpairs(tips, mapping = aes(color = day), 
2        columns = c("total_bill", "time", "sex"), 
3        columnLabels = c("Total_Bill(連續變量)", "Time(離散變量)", "Sex(離散變量)"),
4        lower = list(
5          combo = "dot_no_facet", 
6          discrete = "blank"
7        ),
8        upper = list(
9          combo = "dot_no_facet", 
10          discrete = "ratio"
11        ),
12        diag = list(
13          continuous = "barDiag", 
14          discrete = "barDiag"
15        ),
16        title = "自定義lower,upper,diag(一個連續變量,兩個離散變量)" 
17)

——————————————

往期精彩:

相關焦點

  • 史上最全工程造價常用公式匯總,包含所有造價公式,造價人必備
    史上最全工程造價常用公式匯總,包含所有造價公式,造價人必備綜合運用管理學、經濟學和工程技術等方面的知識與技能,對工程造價進行預測、計劃、控制、核算、分析和評價等的工作過程被稱為工程造價。史上最全工程造價常用公式匯總一共有50多頁,100多個公式,主要有:預備費、工程費、生產性建設項目擬建項目總投資、非生產性建設項目總投資、自有資金利潤率等內容。
  • 史上最全的Excel圖表製作方法來了!
    老闆天天很忙,如果你的報表全是密密麻麻的數字,老闆看了頭暈腦脹。所以你必須要學會製作Excel圖表,用最直觀的方式把報表展示給老闆。今天來進行一次史上最全的柱形圖表製作總結,注意收藏哦~不同項目數量對比用簇狀柱形圖包含多個子項目的合計項目對比用堆積柱形圖
  • 史上最全Excel定義名稱公式的用法
    長按下面二維碼;點擊上面"識別圖中二維碼"然後再點關注,可以收到更多Excel教程;也可加我微信號(掃下面二維碼)或搜索duanzhenyun邀請進微信交流群,讓我們一起學習Excel如下圖,根據銷售金額表做一個普通的折線圖,這樣看著還勉強可以。
  • 「史上最全攻略1」
    2019年7月我因為個人原因離職了,但是因為這篇回答的存在,即使我離職到現在快一年了,陸陸續續還是有很多小夥伴通過私信向我諮詢入職星巴克的相關問題。所以我和星巴克之間並沒有斷開聯繫。——2.員工福利——A.共同福利:a.夥伴券:每月十張,每張可免費兌換任意一杯中杯飲品。月工時64小時以上可獲得全部10張,64小時以下可獲得5張。b.夥伴折扣:購買商品可以打七折:杯子、咖啡豆、咖啡器具等等。很多夥伴的工資都通過買杯子還給公司了,畢竟沒幾個人能抵擋住星巴克杯子的誘惑,有收藏癖的更不是用說了。
  • 史上最全的Excel圖表製作方法來了!
    老闆天天很忙,如果你的報表全是密密麻麻的數字,肯定會被罵的。所以你必須要學會製作Excel圖表,用最直觀的方式把報表展示給老闆。
  • 【進階篇繪圖】之帶P值的箱體圖、小提琴圖繪製(一)
    增加組間顯著性差異p值通過size調整箱體圖線的大小;add='jitter'可以在箱體圖中顯示每個樣品所在的位置,當add='boxplot'添加箱體圖,不能同時使用;palette為調色板,可以自定義顏色,也可以指定雜誌配色;label.y 設置高度。
  • 史上最全的APA格式總結
    每一段的開頭應當按一下鍵盤上的Tab鍵再開始寫而不是直接空格Indent(首行縮進)雙倍行間距 Double Space字體要求Times New Roman字體大小要求11-12號(教授的不同要求)需要有頁眉第一頁的頁眉要有Running head:(你的文章標題的簡版,要求全部大寫)還有頁碼在頁眉的最右邊,而第二頁的頁眉內容不需要
  • 餅圖圓環圖嵌套組合圖
    當我們需要用圖表展示完成率時,除了圓環圖,還有什麼好辦法呢?(長按識別二維碼)效果展示:餅圖圓環圖嵌套組合圖,如下圖所示。1、製圖數據源中的B2單元格的完成率由隨機數構成,如下圖所示。>>推薦閱讀 <<(點擊藍字可直接跳轉)史上最全
  • 史上最全職業移民綠卡面試問題清單
    黨員相關問題(是否是黨員、入黨的原因、負責做什麼) 4. 主申請人職業信息(公司名、公司地址、職位等) 5. 與配偶的婚姻信息(求婚、結婚日期、結過幾次婚等) 6. 主副申請人父母信息(姓名、在哪裡等) 7. 出入境美國(如上次入境美國時間、身份等) 8. 是否用過福利 9. 是否有小孩 10.
  • 九型人格——二號助人型(史上最全知識點)
    他們是九型人格中的最有愛的一群!
  • 你文章中的XY圖和Column圖
    本講的相關配置· 作業系統和配色方案:WIN7 Home Basic
  • 送你一份史上最全的PPT素材資源!
    今天,我就整理一份最全的素材資源集合,有了這些資源,再也不用為了找素材而焦頭爛額了,我們只需按圖索驥即可。(3)字體傳奇網址:http://www.ziticq.com/(1)圖魚Noisetexturegenerator 網址: http://www.noisetexturegenerator.com/(1)PS創意圖
  • 史上最難邏輯題!據說99.9%的人都做不出來……
    同時也給世界留下了寶貴的燒腦財富,史上最難邏輯謎題。對於「世界上最難的邏輯謎題」,至今,哲學家和邏輯學家們都非常迷戀。這個最難謎題的稱號,是Smullyan的同事,麻省理工學院的邏輯哲學家 George Boolos 命名(他的這位同事也挺牛逼的,是邏輯學大師)。史上最難邏輯謎題是這麼說的:
  • 自動突顯最大值和最小值的柱形圖
    今天介紹的自動突顯最大值和最小值的柱形圖,可以自動更新圖表極值。本教程內容較多,擔心記不全的話,可以分享到朋友圈給自己備份一份。(長按識別二維碼)效果展示:自動突顯最大值和最小值的柱形圖,如下圖所示。這個圖表中,有以下幾個特點:最大值用深藍色柱形圖標識最小值用淺紅色柱形圖標識實際數據源更新後,圖表動態自動更新製圖步驟:
  • 史上最全英語面試問題
    Are you a teamplayer?20.你善於團隊合作嗎?21. What motivates youto do your best on the job?21.工作中最能激勵你的是什麼? 22. What is your philosophy towards work?22.你的工作哲學是什麼?23.
  • 一套史上最全的財務Excel資料包!
    首先,它用動圖教你一些excel基礎技巧,如下面這張圖:哈哈,厲害了額,不會佔用你太多時間分分鐘教會你學會excel,同時還有上G系列視頻教程,它們是——(隆重出場)↓↓↓為了幫助大家解決財務工作上的Excel難題,小編這幾天熬夜,做了一系列的表格模板,從很多做Excel的名校老師,拿了一些會計常用的視頻教程整理
  • 一文搞定sizeof筆試面試題
    在面試C/C++相關的崗位時,sizeof操作符幾乎是必考內容,它能檢驗面試者的基本功,所以,只能全對,不能出錯。
  • 2018最新高顏值簡歷模板全這裡了(一鍵套用) | 找實習必備
    【PS】獲取192GPS大禮包【PPT】獲取最全PPT素材庫來了!【CPA】【教師】【普通話】【人力資源】,下載相關考證資源!↓↓↓2017年12月計算機二級、英語四六級備考資源來了!最全PPT素材庫來了!
  • 【說唱乾貨】Freestyle從無到有史上最全教程
    不是每一個好的Rapper都有一張不錯的專輯,但總的來說,你的即興說唱能力直接關係到自己整體的說唱技巧。所以,當你剛開始說唱,請先學習即興說唱。然後你就會像得知了跑步訣竅一樣,很快的踏入正軌。                                                            02                                十個步驟步驟一:開始很容易開始的時候只是要忘掉一切東西和Flow。
  • 史上最全的星巴克點單技巧
    適合早上把自己苦醒,還有比方吃飽飯沒事做的義大利人,會邊喝這個邊閒聊。。以個人經驗,加一大坨糖進去之後,比較能夠入口。。苦與甜的交融,微笑與皺眉的完美搭配。cappuccino的經典搭配是croissant(羊角麵包)。