Principal component analysis (pca) is a great dimension reduction method to reduce large datasets to a smaller set, keeping the key, or principal components. R offers functions to carry out pca with ease, but creating good looking biplots in R can be quite involved, or require additional packages.
I've written a new, better biplot function, which makes creating beautiful looking biplots a breeze. And, its all written in base R, so does not require any additional packages to be installed. Just load the script and start plotting!
Ben's Better Biplot
Ben's Better Biplot is a script to create beautiful looking biplots using base R, without the need to use or install any additional packages. Designed to work with prcomp()
and princomp()
output for principal component analysis (pca), but can also work with other data. The function is compatible with the base biplot()
function, but offers significant enhancements including new features and full customisation of the biplot.
Features
- Quickly create beautiful biplots from pca analysis.
- Uses base R - no need to install other packages.
- Compatible* with base biplot() function.
- Full customisation of the plot.
- Style the plot points based on groups (up to three), or style manually.
- Add legends (automatically generated).
- Add ellipses or convex hulls to grouped data.
- Add circle of equilibrium contribution.
- Plays nicely with layout(), mfrow(), par() and other plot functions.
The code is available on my GitHub: https://github.com/benbell95/better_biplot, and you can load it directly into R using:
# Load better biplot code in R from GitHub
source("https://raw.githubusercontent.com/benbell95/better_biplot/refs/heads/main/r/better_biplot.r")
Once the script is loaded, you can use bb_biplot()
to create better looking biplots:
# pca
p <- prcomp(iris[-5], scale=TRUE)
# Group
gr <- as.factor(iris[,5])
# Plot
bb_biplot(p, scale=0, group=gr, lab_rotation=TRUE, circle.eq=TRUE, legend=TRUE, title.leg="Species")
This should result in the figure shown at the top of this blog post. Easy!
You can fully customise the plot, add ellipses, convex hulls and more. I'll be writing new guides for this function to explain how to use the different features, and they'll be available soon.
For now, check out my GitHub page for further details and to get started: https://github.com/benbell95/better_biplot
Thanks for reading, please leave any comments below.
No comments
Post a Comment
Comments are moderated. There may be a delay until your comment appears.