Principal Component Analysis (PCA) is one of the most powerful techniques in a data scientist’s toolkit.


Principal Component Analysis (PCA) is one of the most powerful techniques in a data scientist’s toolkit. It compresses complex, high-dimensional data into 2D or 3D visuals that are easy to interpret.
In this guide, we will walk through how to run a PCA in R and progressively build publication-ready visualisation plots using ggplot2.
When your dataset has many numeric variables, visualising relationships across all dimensions at once is virtually impossible. PCA solves this by transforming correlated features into a smaller set of uncorrelated variables called Principal Components (PCs).
By plotting PC1 vs. PC2, you can spot clusters, patterns, and outliers in two dimensions while retaining most of the signal in your original dataset.
To follow along, you’ll need a few essential R libraries:
rattle: provides the classic wine dataset — a great benchmark dataset containing the results of 13 chemical analyses of 178 wine samples separated into three different wine types.ggplot2: the gold standard for visualisation in R.dplyr: simplifies data manipulation and data manipulation workflows.car: contains the ellipse() function, which allows us to draw exact mathematical confidence ellipses around our groups.1# Install packages if you haven't already:2# if (!require("rattle")) install.packages("rattle")3# if (!require("ggplot2")) install.packages("ggplot2")4# if (!require("dplyr")) install.packages("dplyr")5# if (!require("car")) install.packages("car")67library(rattle) # Sample wine dataset8library(ggplot2) # Data visualisation9library(dplyr) # Data wrangling10library(car) # Exact ellipse calculations
First, let's load the dataset, separate the type labels from the numerical measurements, and run prcomp(). Note that we set scale. = TRUE so that the data are scaled and the variables with large ranges don't dominate the analysis.
1# --- Load and Prep Data ---2data(wine, package = "rattle")3wine_data <- wine[, -1] # Drop categorical column for PCA4wine_class <- factor(wine$Type) # Store type labels (1, 2, 3)56# --- Perform PCA ---7wine_pca <- prcomp(wine_data, scale. = TRUE)89# --- Extract PC Scores ---10pca_df <- as.data.frame(wine_pca$x[, 1:2])11names(pca_df)[1:2] <- c("PC1", "PC2")12pca_df$Class <- wine_class1314# --- Calculate % Variance Explained ---15var_exp <- wine_pca$sdev^2 / sum(wine_pca$sdev^2)16x_lab <- sprintf("PC1 (%.1f%%)", 100 * var_exp[1])17y_lab <- sprintf("PC2 (%.1f%%)", 100 * var_exp[2])1819# --- Padding function to give plot borders breathing room ---20pad <- function(z, f = 0.05) range(z) + diff(range(z)) * c(-f, f)21x_limits <- pad(pca_df$PC1, 0.05)22y_limits <- pad(pca_df$PC2, 0.05)
To make sure our plots look consistent, we map out shapes, colours, and a helper function to compute 95% confidence ellipses.
1# --- Mapping Colours and Shapes ---2classes <- levels(pca_df$Class)34col_vals <- c("#F8766D", "#00BA38", "#619CFF")[seq_along(classes)]5col_map <- setNames(col_vals, classes)67shape_vals <- c(16, 17, 15)[seq_along(classes)]8shape_map <- setNames(shape_vals, classes)910# --- Helper Function for 95% Confidence Ellipses ---11get_ellipse_coords <- function(df, level = 0.95, segments = 200) {12 cov_mat <- cov(df[, c("PC1", "PC2")])13 center <- colMeans(df[, c("PC1", "PC2")])14 as.data.frame(15 car::ellipse(center = center,16 shape = cov_mat,17 radius = sqrt(qchisq(level, df = 2)),18 segments = segments,19 draw = FALSE)20 )21}2223# --- Pre-calculate ellipse coordinates for each wine class ---24ell_list <- split(pca_df, pca_df$Class)25ell_data <- bind_rows(lapply(ell_list, function(d) {26 coords <- get_ellipse_coords(d, level = 0.95, segments = 200)27 cbind(coords, Class = d$Class[1])28}))29names(ell_data)[1:2] <- c("x", "y")
Now for the fun part! We will build our visualisations progressively, starting from a monochrome view up to custom-shaded ellipses.
Stage 1. Greyscale and shape distinction
Ideal for black-and-white publications or print media where colour isn’t an option (Figure 1).
1p1 <- ggplot(pca_df, aes(PC1, PC2, shape = Class)) +2 geom_point(size = 2, color = "grey40") +3 scale_shape_manual(values = shape_map) +4 xlim(x_limits) + ylim(y_limits) +5 labs(x = x_lab, y = y_lab, shape = "Wine type") +6 theme_bw(base_size = 14)7p189ggsave("wine_pca_stage1.png", p1, width = 7, height = 5.75, dpi = 300)

Figure 1. Greyscale PCA plot.
Stage 2. Colour grouping
Adding colour quickly makes cluster separation clear on digital screens and presentations (Figure 2).
1p2 <- ggplot(pca_df, aes(PC1, PC2, color = Class)) +2 geom_point(size = 2) +3 scale_color_manual(values = col_map) +4 xlim(x_limits) + ylim(y_limits) +5 labs(x = x_lab, y = y_lab, color = "Wine type") +6 theme_bw(base_size = 14)78p2910ggsave("wine_pca_stage2.png", p2, width = 7, height = 5.75, dpi = 300)

Figure 2. Coloured PCA plot.
Stage 3. Outlined confidence ellipses
Adding 95% confidence outlines helps quantify how distinctly separated the groups are (Figure 3).
1p3 <- ggplot(pca_df, aes(PC1, PC2, color = Class)) +2 geom_point(size = 2) +3 geom_path(data = ell_data,4 aes(x = x, y = y, color = Class, group = Class),5 linewidth = 1) +6 scale_color_manual(values = col_map) +7 xlim(x_limits) + ylim(y_limits) +8 labs(x = x_lab, y = y_lab, color = "Wine type") +9 theme_bw(base_size = 14)1011p31213ggsave("wine_pca_stage3.png", p3, width = 7, height = 5.75, dpi = 300)

Figure 3. Coloured PCA plot with ellipses added.
Stage 4. Shaded confidence regions (publication standard)
Combining filled, translucent polygons with sharp boundary lines yields a high-impact, easy-to-read figure (Figure 4).
1p4 <- ggplot(pca_df, aes(PC1, PC2, color = Class, fill = Class)) +2 geom_point(size = 2) +3 geom_polygon(data = ell_data,4 aes(x = x, y = y, fill = Class, group = Class),5 alpha = 0.2, color = NA) +6 geom_path(data = ell_data,7 aes(x = x, y = y, color = Class, group = Class),8 linewidth = 1) +9 scale_color_manual(values = col_map) +10 scale_fill_manual(values = col_map) +11 xlim(x_limits) + ylim(y_limits) +12 labs(x = x_lab, y = y_lab, color = "Wine type", fill = "Wine type") +13 theme_bw(base_size = 14)1415p41617ggsave("wine_pca_stage4.png", p4, width = 7, height = 5.75, dpi = 300)

Figure 4. Coloured PCA plot with shaded ellipses included.
The final plot illustrates how the 178 wine samples partition in two-dimensional space based on 13 measured chemical attributes (such as alcohol content, malic acid, flavonoids, etc.). Together, PC1 and PC2 account for 55.4% of the total variance (36.2% and 19.2%, respectively) across the three cultivar types:
While there is some visible overlap between the 95% confidence regions, reducing the 13 original chemical dimensions down to just two principal components provides substantial visual separation and clearly demonstrates how the three wine varieties differ chemically.
With fairly simple R code, you can go from raw multidimensional data to clean, publication-ready PCA plots. By precalculating exact confidence regions using car::ellipse(), you retain full architectural control over aesthetics while maintaining mathematical precision.

Molecular biology, agronomy, and experimental design — translating wet-lab questions into sound statistical plans.
LinkedIn →Book a free 20-minute consultation. We'll scope your analysis and tell you exactly what it takes to publish.