MGHome page

GWAS course

Course map

0 of 64 steps done

Start with step 0.1Install R

Saved in this browser only.

Step 5.5

Module 5 · Population structure · step 5 of 7

5.5Plot the reference and projected study

Commands tested on Windows

In short

We plot the first three principal components, each a number summarising one pattern of genetic variation, in three pairs. We show reference groups with labels and symbols and add the study samples to see how their genetic backgrounds compare.

Do this

You should see: A labelled plot of the reference with the projected study.

Command

Module setup, needed before this step

R: module setup

source("R/guided.R")cfg <- guided_init()

R command

Type or paste into the RStudio console.

1ref <- guided_table(paste0(guided_path(cfg, "5.4", "ref_scores"), ".sscore"))study <- guided_table(paste0(guided_path(cfg, "5.4", "study_scores"), ".sscore"))metadata <- guided_table(file.path(cfg$data_dir, "pca_reference", "ref1000g_grch38.psam"))2group <- metadata$SuperPop[match(ref$IID, metadata$IID)]levels <- sort(unique(group)); code <- match(group, levels)colours <- c("#0072B2", "#D55E00", "#009E73", "#CC79A7", "#E69F00")3plot_components <- function(x, y, file) {  png(file, width = 1400, height = 850, res = 140)  par(mar = c(5, 4.5, 4, 9))  plot(as.numeric(ref[[paste0("PC", x, "_AVG")]]), as.numeric(ref[[paste0("PC", y, "_AVG")]]), col = colours[code], pch = code,    xlab = paste0("Reference PC", x, " score"), ylab = paste0("Reference PC", y, " score"),    main = paste0("GRCh38 reference and projected simulated study: PC", x, " and PC", y))  # Add the study samples and a key for the groups. The key sits outside the plot, on the right, so it hides no points.  points(as.numeric(study[[paste0("PC", x, "_AVG")]]), as.numeric(study[[paste0("PC", y, "_AVG")]]), pch = 20, cex = 0.4, col = "#333333")  legend("topright", inset = c(-0.21, 0), xpd = TRUE, legend = c(levels, "Study projection"), col = c(colours[seq_along(levels)], "#333333"), pch = c(seq_along(levels), 20), cex = 0.8)  invisible(dev.off())}4files <- c(guided_path(cfg, "5.5", "reference_projection.png"),  guided_path(cfg, "5.5", "reference_projection_pc1_pc3.png"),  guided_path(cfg, "5.5", "reference_projection_pc2_pc3.png"))plot_components(1, 2, files[1]); plot_components(1, 3, files[2]); plot_components(2, 3, files[3])5for (file in files) cat("The plot was saved to ", file, "\n", sep = "")
  1. Note 1: Read both score tables and the reference group labels.
  2. Note 2: Match the reference labels to samples and choose group symbols and colours.
  3. Note 3: Define one plotting function, so that all pictures use the same symbols, colours and key.
  4. Note 4: Save the picture for PC1 and PC2, then the two extra pictures for PC1 and PC3 and for PC2 and PC3.
  5. Note 5: Print the location of each picture.

You need

The score files from step 5.4, and the reference sample table.

What we do

Draw three plots of the first three reference axes: PC1 against PC2, PC1 against PC3 and PC2 against PC3. Each reference group has its own label and symbol, and the study samples are added on top. All three plots use the same symbols, colours and key.

Why

A plot of two PCs helps us see large differences between samples. Later PCs can show patterns that PC1 and PC2 hide. This is why we also plot PC3 against each of the first two. A difference can also come from the genotyping platform, from missing data or from allele errors. The study points are projected scores. They are not a separate PCA. The groups use symbols as well as colour, so the plot stays readable without colour.

Illustration in preparation

Alt text: Reference samples form labelled genetic-variation clusters; most simulated study samples overlap the European reference pattern.

Illustration in preparation

Alt text: Saved reference PCA image opened from RStudio Files on Windows, showing labelled axes and reference groups.

Illustration in preparation

Alt text: Saved reference PCA image opened from RStudio Files on macOS, showing labelled axes and reference groups.
PLINK terminal equivalent. Optional: you do not need it for the course.

Not applicable: this step needs no PLINK command. The R chunk is the complete command.

R reads or calculates the displayed values without changing the genotype files.

Expected result

Show the expected result

A labelled plot of the reference with the projected study. Most study samples fall on the European reference pattern. A small number extend elsewhere. The key is outside the plot, on the right, so it hides no points. A PC can flip its sign (its direction on the axis) without changing its meaning. R saves three pictures as PNG files and prints the path of each one. The first picture shows PC1 and PC2. The other two show PC1 with PC3 and PC2 with PC3, with the same colours and symbols. It does not show the pictures in the console. To see it, open the file from the Files pane of RStudio (click the file name, then choose "View File").

The tested PLINK version is defined in config.R and recorded in software_versions.txt. Validation: executable chunks and the expected counts passed on Windows.

If something goes wrong

If something goes wrong

Stop at the first error message. Check the input file named in the message and the previous step. Keep the command and the console log. Do not use files from a different dataset version. See troubleshooting (opens in a new tab).

</details>

Optional: a 3D plot with ellipses

<details><summary>Show the optional 3D plot</summary>

This box is not part of the main path. No later step uses it. The code is not run by default. It draws the three first components in one rotating 3D picture. A 95% ellipse is drawn around each reference group. An ellipse shows where about 95% of the points of a group are expected to lie. The code needs the package rgl, which step 0.5 does not install. To install it once, type install.packages("rgl") in the R console. On macOS, rgl may also need the free program XQuartz. If the package does not install, or no window opens, skip this box. The code does nothing when rgl is missing.

# Optional. Needs the rgl package: install.packages("rgl")
if (requireNamespace("rgl", quietly = TRUE)) {
  # 1. Collect the scores of the first three components for the reference samples.
  scores <- cbind(as.numeric(ref$PC1_AVG), as.numeric(ref$PC2_AVG), as.numeric(ref$PC3_AVG))
  # 2. Draw the reference samples in 3D, with the colours used in the 2D plots.
  rgl::plot3d(scores, col = colours[code], size = 4, xlab = "PC1", ylab = "PC2", zlab = "PC3")
  # 3. Add one 95% ellipse for each reference group.
  for (i in seq_along(levels)) {
    group_scores <- scores[code == i, , drop = FALSE]
    rgl::plot3d(rgl::ellipse3d(cov(group_scores), centre = colMeans(group_scores), level = 0.95),
      col = colours[i], alpha = 0.15, add = TRUE)
  }
} else {
  message("The rgl package is not installed. Skip this optional plot.")
}

Quick check

Does overlap with a reference group prove a person's nationality?

Show the answer

No. The plot summarises genetic variation compared with a chosen reference. It does not show nationality or ethnicity.

Files created

s5-5_reference_projection.png (PC1 and PC2), s5-5_reference_projection_pc1_pc3.png (PC1 and PC3) and s5-5_reference_projection_pc2_pc3.png (PC2 and PC3).