---
disqus: ahb0222
GA : G-CQ4L16KHK4
---
# ggplot2邊緣圖_ggExtra
> [color=#40f1ef][name=LHB阿好伯, 2021/04/26][:earth_africa:](https://www.facebook.com/LHB0222/)
###### tags: `R` `ggplot2` `可視化`
[TOC]

今天來介紹ggplot2的邊緣圖的相關套件ggExtra
使用[鳶尾花iris數據集](https://archive.ics.uci.edu/ml/datasets/iris)來做範例
其數據集包含了150個樣本,都屬於鳶尾屬下的三個亞屬,分別是山鳶尾(setosa)、變色鳶尾(versicolor)和維吉尼亞鳶尾(virginica)分別包含了花萼和花瓣的長度和寬度資料

|Sepal.Length |Sepal.Width |Petal.Length |Petal.Width |Species|
| :---: | :---: | :---: | :---: | :---: |
| 5.1 | 3.5 | 1.4 | 0.2 | *setosa* |
| 4.9 | 3.0 | 1.4 | 0.2 | *setosa* |
| 4.7 | 3.2 | 1.3 | 0.2 | *setosa* |
| 4.6 | 3.1 | 1.5 | 0.2 | *setosa* |
| 5.0 | 3.6 | 1.4 | 0.2 | *setosa* |
| 5.4 | 3.9 | 1.7 | 0.4 | *setosa* |
| 4.6 | 3.4 | 1.4 | 0.3 | *setosa* |
# 載入所需套件
```r=
#install.packages("ggExtra") #第一次使用需安裝
#install.packages("ggplot2")
library(ggplot2)
library(ggExtra)
```
## 基本圖形
首先先繪製最基本的散佈圖
```r=+
p1 <- ggplot(data = iris,
mapping = aes(x = Sepal.Length, y = Sepal.Width, colour = Species)) + #設定資料集與映射資料
geom_point()
p1
```

使用ggExtra的ggMarginal函數繪製邊緣圖
```r=+
ggMarginal(p1)
```
預設是繪製密度圖

可以以添加變數` type = "histogram"` or ` type = "boxplot"` or `type = "violin"`更改為直方圖、箱型圖或小提琴圖
```r=+
p3 <- ggMarginal(p1, type = "histogram")
p3
```

```r=+
p4 <- ggMarginal(p1, type = "boxplot")
p4
```

```r=
p5 <- ggMarginal(p1, type = "violin")
p5
```

或是`type = "densigram"`
可以繪製直方圖與密度圖的結合
```r=+
p6 <- ggMarginal(p1, type = "densigram")
p6
```

## 邊緣圖美化
### 顏色修改
添加`groupColour = TRUE, groupFill = TRUE`變數可以使的邊緣圖與散佈圖有一樣的顏色
```r=
p7 <- ggMarginal(p1,type = "boxplot",groupColour = TRUE, groupFill = TRUE)
p7
```

### 額外參數
添加`xparams = list(bins=10), yparams = list(bins=10)`參數可以修改直方圖的組數
```r=
p8 <- ggMarginal(p1, type = "histogram",xparams = list(bins=10), yparams = list(bins=10))
p8
```

### 更改圖例位置
我們可以將圖利更改為下方這樣就可以騰出位置給邊緣圖
```r=
p8 <- p1 + theme(legend.position="bottom")
p9 <- ggMarginal(p8,type = "boxplot",groupColour = TRUE, groupFill = TRUE)
p9
```

更進一步我們也可以自訂圖例位置與外觀
```r=+
p10 <- p1 + theme(legend.position = c(0.75, 0.95), #自訂圖例位置
legend.background = element_rect(fill = NA), #去除圖例背景
legend.title = element_blank(), #刪除圖例標籤
legend.direction = "horizontal") #將圖例設定為水平
p10
p11 <- ggMarginal(p10,type = "boxplot",groupColour = TRUE, groupFill = TRUE)
p11
```

🌟若是有興趣有可以到這下面的網站玩玩看
https://daattali.com/shiny/ggExtra-ggMarginal-demo/

🌟全文可以至下方連結觀看或是補充
全文分享至
https://www.facebook.com/LHB0222/
https://www.instagram.com/ahb0222/
有疑問想討論的都歡迎於下方留言
喜歡的幫我分享給所有的朋友 \o/
有所錯誤歡迎指教
# [:page_with_curl: 全部文章列表](https://hackmd.io/@LHB-0222/AllWritings)
