https://friendly.github.io/ggbiplot/
A ggplot2 based biplot for principal components-like methods
https://friendly.github.io/ggbiplot/
biplot data-visualization dimension-reduction principal-component-analysis
Last synced: 2 months ago
JSON representation
A ggplot2 based biplot for principal components-like methods
- Host: GitHub
- URL: https://friendly.github.io/ggbiplot/
- Owner: friendly
- Fork: true (vqv/ggbiplot)
- Created: 2022-09-03T20:22:54.000Z (over 3 years ago)
- Default Branch: master
- Last Pushed: 2025-09-16T20:12:36.000Z (4 months ago)
- Last Synced: 2025-10-22T03:49:11.864Z (3 months ago)
- Topics: biplot, data-visualization, dimension-reduction, principal-component-analysis
- Language: HTML
- Homepage: https://friendly.github.io/ggbiplot/
- Size: 6.59 MB
- Stars: 12
- Watchers: 1
- Forks: 0
- Open Issues: 3
-
Metadata Files:
- Readme: README.Rmd
Awesome Lists containing this project
- awesome-ggplot2 - ggbiplot - like methods (Data and models)
README
---
output: github_document
---
[](https://CRAN.R-project.org/package=ggbiplot)
[](https://github.com/friendly/ggbiplot)
[](https://cran.r-project.org/package=ggbiplot)
```{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
**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")
```