forked from vqv/ggbiplot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathREADME.Rmd
263 lines (202 loc) · 8.94 KB
/
README.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
---
output: github_document
---
<!-- README.md is generated from README.Rmd. Please edit that file -->
<!-- badges: start -->
[![CRAN status](https://www.r-pkg.org/badges/version/ggbiplot)](https://CRAN.R-project.org/package=ggbiplot)
[![Last Commit](https://img.shields.io/github/last-commit/friendly/ggbiplot)](https://github.com/friendly/ggbiplot)
[![Downloads](https://cranlogs.r-pkg.org/badges/ggbiplot)](https://cran.r-project.org/package=ggbiplot)
<!-- badges: end -->
<!-- This repo for the **ggbiplot** package -->
<!-- was forked from [https://github.com/vqv/ggbiplot](https://github.com/vqv/ggbiplot) by Vince Vu, which has been dormant -->
<!-- since 2015. -->
<!-- The goal is to complete that development and publish a new version on CRAN with Vince Vu as the principal author. -->
<!-- There is also an [experimental branch](https://github.com/friendly/ggbiplot/tree/experimental) which attempts to -->
<!-- simplify the code, but this has some unresolved problems. -->
```{r, echo = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
message = FALSE,
warning = FALSE,
comment = "#>",
fig.height = 6,
fig.width = 6,
fig.path = "man/figures/README-"
)
options(digits = 3)
# find the current git branch
# from: https://gist.github.com/hadley/3427128
# kludge because find_git() not available
git_branch <- function() {
# git <- "C:/Program Files/Git/bin/git.exe"
git <- Sys.which("git")
system2(git, "symbolic-ref --short -q HEAD", stdout = TRUE, stderr = FALSE)
}
```
# ggbiplot <img src="man/figures/logo.png" height="200" style="float:right; height:200px;"/>
**Version** `r packageVersion("ggbiplot")` ( `r git_branch()` branch )
This package provides a `ggplot2` implementation of the biplot, a simultaneous
plot of scores for observations and vectors for variables for principal component-like analyses.
The package provides two main functions: `ggscreeplot()` and `ggbiplot()`.
`ggbiplot` aims to be a drop-in replacement for the standard R function `stats::biplot()` with extended functionality
for labeling groups, drawing a correlation circle, and adding data ellipsoids.
It also supports PCA-like objects calculated by `FactoMineR::PCA()`, `ade4::dudi.pca()` and `MASS::lda()`.
The package was originally developed by Vince Vu at [https://github.com/vqv/ggbiplot](https://github.com/vqv/ggbiplot).
That development was supported in part by NSF Postdoctoral Fellowship DMS-0903120 from 2009-2012.
The current version, now on CRAN, will be the locus of further development.
## Installation
You can install the latest CRAN version, or install from GitHub as shown below.
+-------------------+-----------------------------------------------------------------+
| CRAN version | `install.packages("ggbiplot")` |
+-------------------+-----------------------------------------------------------------+
| GitHub | `remotes::install_github("friendly/ggbiplot")` |
| `master` | |
+-------------------+-----------------------------------------------------------------+
## Examples
Load packages:
```{r}
library(ggplot2)
library(ggbiplot)
library(dplyr)
library(corrplot)
# set ggplot2 theme
theme_set(theme_minimal(base_size = 14))
```
### Crime data
The `crime` data gives rates of various serious crimes in each of the 50 U. S. states,
originally from the United States Statistical Abstracts (1970).
Let's take a quick look at the correlations among these, using `corrplot::corrplot()`
and showing each correlation by an ellipse whose eccentricity and shading represents the value of
the correlation.
```{r crime-corrplot}
data(crime)
crime |>
dplyr::select(where(is.numeric)) |>
cor() |>
corrplot(method = "ellipse", tl.srt = 0)
```
The correlations are all positive. Note also that the variables in the dataset
are ordered in seriousness or violence, ranging from murder to auto theft.
Carry out a PCA:
```{r crime-pca}
crime.pca <-
crime |>
dplyr::select(where(is.numeric)) |>
prcomp(scale. = TRUE)
crime.pca
```
The biplot, using default scaling (standardized components), and labeling the
states by their state abbreviation:
```{r crime-biplot0}
ggbiplot(crime.pca,
labels = crime$st ,
circle = TRUE,
varname.size = 4,
varname.color = "red")
```
The directions of the principal components are arbitrary; we are free to reflect
the variable vectors and component scores to facilitate interpretation.
Also, there seem to be differences among regions of the U.S., which can be
visualized using data ellipses for the component scores. The `groups` argument
allows the observations to colored by group and to summarized by groups.
```{r crime-biplot1}
crime.pca <- reflect(crime.pca)
ggbiplot(crime.pca,
groups = crime$region,
labels = crime$st,
labels.size = 4,
var.factor = 1.4,
ellipse = TRUE, ellipse.level = 0.5, ellipse.alpha = 0.1,
circle = TRUE,
varname.size = 4,
varname.color = "black") +
labs(fill = "Region", color = "Region") +
theme(legend.direction = 'horizontal', legend.position = 'top')
```
The interpretation of the data is now clear.
* The first dimension,
accounting for 58.8% of variance, can be seen to represent **overall
crime rate**, with Nevada (NV) at the high end and North Dakota (ND),
South Dakota (SD) and West Virginia (WV) at the low end.
* The second dimension, accounting for 17.7% of variance represents
a contrast between
**personal crime vs. property crime**. On this dimension, Massachusetts (MA),
Rhode Island (RI) are opposed to Mississippi (MS), Alabama (AL), Louisiana (LA) and South
Carolina (SC).
* The regions are represented by the differences in the centers of the
data ellipses for the scores. Southern states are highest on murder,
assault and rape, while the Northeast states are highest on auto theft
and larceny.
* In this standardized view, the angles between variable vectors approximate
the correlations among the variables, according to $\cos (\text{angle}) \approx r$.
Thus, `murder` and `auto`, nearly $90^o$ reflect a near 0 correlation.
### Wine data
The `wine` data contains results of a chemical analysis of wines grown in the same region in Italy,
derived from three different cultivars. The analysis determined the
quantities of 13 chemical constituents found in each of the three types of wines.
The grape varieties (cultivars), **barolo**, **barbera**, and **grignolino**, are given in `wine.class`.
What can we understand about the differences among these wines from a biplot?
```{r wine-screeplot}
data(wine)
wine.pca <- prcomp(wine, scale. = TRUE)
ggscreeplot(wine.pca)
```
Hmm. The screeplot shows that more than two dimensions are necessary to account for most of the variance.
Plot the first two PCA dimensions, accounting for 55% of the variance.
```{r wine-biplot}
ggbiplot(wine.pca,
obs.scale = 1, var.scale = 1,
groups = wine.class,
varname.size = 4,
ellipse = TRUE,
circle = TRUE) +
labs(fill = "Cultivar", color = "Cultivar") +
theme(legend.direction = 'horizontal', legend.position = 'top')
```
The three cultivars are arranged along the first dimension, in the order barolo < grignolino < barbera.
These are distinguished largely by a contrast between (`Phenols`, `Flav`) vs. (`NonFlavPhenols`, `AlcAsh`).
The second dimension is represented by the cluster of variables `Mg`, `Alcohol`, `Ash`, `Color`, which distinguishes
grignolino from the other two.
### Iris data
The classic iris data is widely used for examples of multivariate analysis and biplots, so let's use it here.
```{r iris-pca}
data(iris)
iris.pca <- prcomp (~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width,
data=iris,
scale. = TRUE)
summary(iris.pca)
```
Plot the first two dimensions:
```{r iris-biplot0}
iris.gg <-
ggbiplot(iris.pca, obs.scale = 1, var.scale = 1,
groups = iris$Species, point.size=2,
varname.size = 5,
varname.color = "black",
varname.adjust = 1.2,
ellipse = TRUE,
circle = TRUE) +
labs(fill = "Species", color = "Species") +
theme_minimal(base_size = 14) +
theme(legend.direction = 'horizontal', legend.position = 'top')
iris.gg
```
It is possible to add annotations to the biplot by making use of the fact that `ggplot()` returns a lot of
information in the `"gg"` object. In particular, the `$data` component contains the scores on the principal
components that are plotted as points here.
Here we add direct labels for the groups and suppress the legend.
```{r iris-labs}
# get means of coordinates by group
group.labs <-
iris.gg$data |>
summarise(xvar = mean(xvar),
yvar = mean(yvar), .by = groups)
group.labs
```
Now, just use `geom_label` to draw labels for the groups.
```{r iris-biplot1}
iris.gg + geom_label(data = group.labs,
aes(x = xvar, y=yvar, label=groups),
size = 5) +
theme(legend.position = "none")
```