Lecture 9 — R Graphics and Statistics: Making Data Talk

Statistics and Graphics: From Counts to Conclusions

Fighting Cancer with Transcriptomics 2026

2026-11-02

📊 From Counts to Conclusions

🗺️ Where Lecture 9 sits

  • Lectures 1, 2, 4: course intro, Linux, text streams, pipelines
  • Lectures 5, 6: R syntax, data types, data structures — the R track
  • Lectures 3, 7, 8: bulk RNA-seq — design, FASTQ QC, STAR alignment, featureCounts
  • Lecture 9: R Graphics & Transcriptomic Statistics — statistics that turn numbers into claims, plots that show them.

1. Review from Lecture 8

1. Review from Lecture 8

2. Descriptive Statistics

3. Shape, Distribution & Normality

4. p-value & Statistical Tests

5. Correlation & Regression

6. Statistics Practice

7. From Numbers to Figures

8. The Common Plots

9. Reading a ggplot2 Call

10. Export for Publication

11. Graphics Practice

⚡ Q1: Find the counts for gene X — which line gets the row?

  • A. df[2, ]
  • B. df[3, ]
  • C. df[, 2]
  • D. df$X

✅ B — df[3, ] is the whole row for gene X

  • A is the 2nd row — BRCA1, not X. The comma is right; the number is the wrong gene.
  • C is the 2nd column as a vector: 1200 450 89. The comma comes before the 2.
  • D is the quiet trap: $ takes a column by name, and there is no column called X, so it returns NULL with no error.

Tip

The way you do it in real code: df[df$gene == "X", ]. Row names are not row numbers, so index by a condition.

A data frame gives you a row only when the comma is there: [row, column]

⚡ Q2: Which line gets the counts, not the wrapper?

  • A. qc_report["umi_counts"]
  • B. qc_report[["umi_counts"]]
  • C. qc_report$sample_name
  • D. qc_report[1]

✅ B — [[ ]] unwraps, [ ] keeps the wrapper

  • A single brackets keep the wrapper: the printout starts with $umi_counts, then the numbers.
  • C $ picks by name, and sample_name is a string: chr "Visium_HD_01", not the counts.
  • D [1] picks by position and keeps the wrapper: List of 1 with $sample_name.

Note

Use [[ ]] when you want the value, [ ] when you want a smaller list.

str() shows the difference immediately.

⚡ Q3: Which line averages only the measured spots?

  • A. mean(umi, rm.na = TRUE)
  • B. mean(umi, na.rm = TRUE)
  • C. mean(!is.na(umi))
  • D. mean(umi, na.rm = NA)

✅ B — the flag is spelled na.rm, and it must be TRUE

  • A mean() reads na.rm. rm.na lands in ... and is ignored, so the NA stays and the result is NA.
  • C !is.na(umi) is a logical vector: TRUE TRUE FALSE TRUE TRUE. Averaging it gives the share of measured spots, 0.8, not the counts.
  • D the flag has to be TRUE. isTRUE(NA) is FALSE, so nothing is dropped and the answer stays NA.

Count the holes first, then decide. na.rm = TRUE is a choice you report, not a default.

A number means nothing on its own

A p-value, not a p-list.

— the statistician’s rule of thumb, on this deck’s own theme

One count answers one question. Statistics is what lets us say:

  • what the data looks like (descriptive)
  • what the data is likely to be (distribution)
  • what we can claim from it (inference)

Today: 8 tools, in the order you use them.

🧰 The statistician’s toolbox

  1. Describe: mean, median, sd, IQR
  2. Observe the shape: is it a normal distribution?
  3. Check normality: Shapiro-Wilk, Q-Q plot
  4. Choose a test: parametric or non-parametric
  5. Read the p-value
  6. Correct for multiple testing
  7. Correlate and regress
  8. Plot it — devices, ggplot2, publication figures

2. Descriptive Statistics

1. Review from Lecture 8

2. Descriptive Statistics

3. Shape, Distribution & Normality

4. p-value & Statistical Tests

5. Correlation & Regression

6. Statistics Practice

7. From Numbers to Figures

8. The Common Plots

9. Reading a ggplot2 Call

10. Export for Publication

11. Graphics Practice

🎯 The problem: seven spots — how do you describe them?

  • what’s the range of our data? — the span
  • what is a typical spot? — the average
  • how spread out are the counts? — the spread

The Range — min to max

The Center — where the middle is

  • mean: add them, divide by how many
  • median: the middle value, after sorting

Quartiles — the median of each half

  • Q1: the median of the lower half
  • Q3: the median of the upper half

Two ways to choose the halves. Keeping the median in both halves gives 3 and 14 — what R’s quantile(), fivenum() and boxplot() report. Excluding the median is the calculator rule: lower half 1, 2, 4 → 2, upper half 8, 20, 40 → 20.

Interquartile range (IQR) — the middle half

  • Q1: the lowest 25% of the spots
  • Q3: the highest 25% of the spots
  • IQR: Q3 − Q1 — the spread of the middle half

The Spread — how far it is from the center

Variance — spread distance in squared units

\[v = \frac{1}{n-1}\sum_{i=1}^{n}(x_i - \bar{x})^2\]

Why variance?

  • Tests need variance: t-tests, DE models,…
  • Make counts usable for clustering and PCA.
  • Variable-gene step uses genes with the highest variance

📏 Standard deviation — the deviation from the mean

📏 sd — the average distance from the mean

\[s = \sqrt{\frac{1}{n-1}\sum_{i=1}^{n}(x_i - \bar{x})^2}\]

Why standard deviation?

  • the typical range — sd sets the band mean − sd to mean + sd; inside = typical, outside = stands out → p-value
  • the summary table — every group reports mean ± sd, and Shapiro-Wilk tests the normal distribution sd defines

🔍 variance vs sd — same information, two units

⚖️ sd is what decides a claim

⚡ Q1: Seven tumor spots, mean 11.57. You want one number saying how typical a spot is, in UMI counts. Which?

  • A. var(counts)
  • B. sd(counts)

✅ B — sd is the spread in the same units as the counts

  • B sd is in counts, so mean ± sd is a band the reader can check against the dots.
  • A variance is squared counts — for tests and models, not for reporting.

Report the sd, keep the variance for the model.

⚡ Q2: mean(tight) and mean(wide) are both 11. Which line shows the groups are different?

  • A. median(tight) vs median(wide)
  • B. sd(tight) vs sd(wide)
  • C. length(tight) vs length(wide)
  • D. sum(tight) vs sum(wide)

✅ B — same centre, five times the spread

  • A both medians are 11, so the middle does not tell the groups apart.
  • C both groups have 5 spots; the same n says nothing about spread.
  • D both sums are 55, so the total is identical too.
  • B sd is the only number that separates them: a tight group is repeatable, a wide group is noisy

Note

The mean is the same number; the data is not the same data.

⚡ Q3: One 500 joins nine small counts. Which number moves most?

  • A. the median
  • B. the mean
  • C. both move by the same amount
  • D. neither: the centre is fixed

✅ B — the mean carries 500, the median ignores its size

  • A the median sees only the middle two positions: 6.5.
  • C the mean absorbs 500, the median gains nothing — not symmetric.
  • D the centre moves by 48.9. That gap is the finding.
  • B the mean adds every value, so 500 enters as 500 / 10 = 50 per spot.

Tip

Report both. If mean and median sit far apart, that gap is the finding.

Too lazy? R got you covered!

✅ Summary

  • three questions: the span, the typical spot, the spread
  • range = min to max · mean = add and divide · median = middle
  • quartiles = median of each half · IQR = the middle 50%
  • variance = squared units, for tests · sd = the data’s units, for reporting
  • mean + median together show the shape — one outlier moves the mean
  • summary() prints the whole set

3. Shape, Distribution & Normality

1. Review from Lecture 8

2. Descriptive Statistics

3. Shape, Distribution & Normality

4. p-value & Statistical Tests

5. Correlation & Regression

6. Statistics Practice

7. From Numbers to Figures

8. The Common Plots

9. Reading a ggplot2 Call

10. Export for Publication

11. Graphics Practice

🎯 The problem: same mean, three different tumors

Three tumors can have the same average UMI count and be completely different data.

🧐 sd ranks the spread, not the shape

  • sd sorts the three by spread: tumor2 widest, tumor3 tightest.
  • sd is one number — how far the counts sit from the mean, not where they sit.
  • tumor3 has a tail to the left, and sd only reports that it is tight.

So what should we do?

The shape is the information

It matters because the most common tests assume this shape. If the data is normally distributed, those tests work. If it is not, those tests can lie.

Note

UMI counts are usually not normally distributed: many low-count spots, a few very high ones. Long tail on the right.

Symmetric — tumor1

Many measurements pile up in the middle and thin out evenly on both sides.

That shape is called normal — the bell curve.

  • the counts sit evenly on both sides of the middle
  • mean ≈ median — the two lines land on the same spot

Right-skewed — tumor2

  • twelve counts climb from 1 to 9, one count sits far above
  • the high count drags the mean up — the median stays with the pile
  • mean > median

Left-skewed — tumor3

  • ten counts pile at the high end, a low tail runs to the left
  • the low tail drags the mean down — the median stays with the pile
  • mean < median

Shapiro-Wilk test

One number, one p-value:

  • p > 0.05 → no evidence against normal. Treat it as a normal distribution.
  • p ≤ 0.05 → the data is not normal. Do not use normal-distribution tests.

Note

A Q-Q plot is the visual version: points curving away at the end mean a real tail.

A Q-Q plot

Read the shape from the plot before choosing a test.

✅ Summary

  • sd ranks the spread, not the shape
  • shape = mean vs median: mean ≈ median symmetric · mean > median right · mean < median left
  • the common tests assume the normal shape — UMI counts are usually right-skewed
  • Shapiro-Wilk gives the number, the Q-Q plot the picture — same check
  • p > 0.05 → treat as normal · p ≤ 0.05 → not normal, use the rank test

4. p-value & Statistical Tests

1. Review from Lecture 8

2. Descriptive Statistics

3. Shape, Distribution & Normality

4. p-value & Statistical Tests

5. Correlation & Regression

6. Statistics Practice

7. From Numbers to Figures

8. The Common Plots

9. Reading a ggplot2 Call

10. Export for Publication

11. Graphics Practice

What a p-value is

…the p-value is the probability of obtaining test results at least as extreme as the result actually observed, under the assumption that the null hypothesis is correct.

FB: @Statisticss · IG: @StatisticsForYou — image via Google Images (thumbnail source)

Important

p is not the probability the hypothesis is true.

It answers “what are the chances of getting a result this extreme by pure randomness?”.

p from 0.5 down to 0.001

  • p = 0.5 → this result is common under no effect. Not evidence.
  • p = 0.1 → 1 in 10 under no effect. Not evidence.
  • p = 0.05 → the decision line. 5 in 100 under no effect.
  • p = 0.03 → if the groups were truly the same, this happens about 3 times in 100
  • p = 0.01 → 1 in 100 under no effect.
  • p = 0.001 → 1 in 1,000 under no effect.

⚠️ The problem: 20,000 genes

  • A gene with no difference still gets a p-value. p is defined under no effect, so a result this extreme happens 5 times in 100.

Test 20,000 genes at p < 0.05, and 1,000 will pass by chance alone. Not good.

Important

Every transcriptomics analysis tests thousands of features. Without a correction, you are not discovering — you are sorting noise.

The new threshold — Why divide by 20,000?

  • 0.05 = 1 in 20 fluke chance for one test
  • 20,000 = number of tests
  • 1 in 20 ÷ 20,000 = 1 in 400,000: the whole analysis keeps 1 in 20

Bonferroni — strict

Tip

Simple BUT very hard to pass.

It kills real findings too.

Benjamini-Hochberg — the usual choice

Control the false discovery rate (FDR): the share of your “significant” list that is noise.

Important

BH is the standard in transcriptomics.

Where do p-values come from?

p is not a number you choose. It is the output of a test.

Two decisions come before the test:

  • The unit — what varies independently
  • The test — the question, and the shape of the data

⚠️ The problem: 80 spots, 4 patients

The question: is this gene higher in tumor?

The data we have is spots. The claim we want is about patients.

Every test in the book

  • Student t
  • Welch t
  • paired t
  • Wilcoxon
  • Wilcoxon signed-rank
  • sign test
  • bootstrap
  • permutation
  • ANOVA
  • Welch ANOVA
  • Kruskal-Wallis
  • Friedman
  • MANOVA
  • chi-square
  • Fisher
  • G-test
  • Poisson
  • negative binomial
  • Pearson
  • Spearman
  • Kendall
  • linear regression
  • logistic regression
  • Levene
  • Bartlett
  • Fligner
  • Kolmogorov-Smirnov
  • DESeq2
  • edgeR
  • limma-voom
  • …

Note

Every name is a valid test. Most of them do not answer this question, and the question itself does not say which one to run.

An example

p-value = 1.772e-07 — far below 0.05, so the result is significant. Means 26.200 vs 20.125, a difference of 6.075.

You reported this gene expressed MORE in tumor cohorts.

In reality, the pooled p is a pitfall

Patient 1 and patient 3 sit at the same level: 28.00 and 28.07. Run on the 4 patients, p = 0.831.

Important

Spots are not independent observations. Pooling them makes the sample size huge and the p-value tiny — the number got smaller, the claim did not get stronger.

The test has to be run on the unit the experiment was built on.

Normal distribution tests, and their backup

Question Normal distribution Any data
2 groups t-test Wilcoxon
2 groups, same subject twice paired t Wilcoxon signed-rank
3+ groups ANOVA Kruskal-Wallis

Parametric = assumes the normal distribution.

Non-parametric = assumes nothing. Uses ranks, not values.

The data — check for distribution

p1 p2 p3 p4
condition control control tumor tumor
distribution normal skewed right normal skewed right
mean 28.00 17.50 28.07 20.60
median 28 17 28 17

p2 and p4 are right-skewed: their hot spots drag the mean right of the median.

2 groups, different conditions — treatment vs control

Normal data → t-test

Any data → Wilcoxon

Both say no difference.

A gap is not enough — spread decides

pair gap sd t p
p4 vs p2 3.1 6.45 · 1.28 1.51 0.164
p2 vs p3 10.6 1.28 · 1.55 −28.77 3.205881e-35

Important

A statistic is a signal-to-noise judgement. More spots shrink the noise, so a smaller gap can become convincing.

2 groups, same subject — pre vs post

Same patient, biopsied before and after treatment: 10 spots.

The same data answers two questions. Paired: p = 0.0002025. Unpaired: p = 0.5095. Pairing removes the spot-to-spot spread, so the difference carries more weight.

3+ groups — ANOVA

All three are normal, so ANOVA is fair: p < 2e-16.

3+ groups — ANOVA: result and pairwise

Patients 1 and 3 express the gene at the same level (28.0 and 28.07); patient 5 expresses it lower (20.0).

Patient 5 is below patients 1 and 3 (p < 2e-16 each); patients 1 and 3 do not differ (p = 0.9).

3+ groups — Kruskal-Wallis

Patient 2 and patient 4 are skewed, so Kruskal-Wallis takes all four: p = 7.477e-12.

3+ groups — Kruskal-Wallis: Which pair differs

  • Insignificant pairs:
    • p1 vs p3
    • p2 vs p4
  • Significant pairs:
    • p2 vs p1
    • p2 vs p3
    • p4 vs p1
    • p4 vs p3

A category cannot be averaged

Every test so far takes one number per spot.

Some questions ask how many spots sit in a category.

Counting data — the question

The answer is a table of counts, not a mean.

Expected count = row total × column total ÷ total spots.

Chi-square — big counts

Expected counts stay above 5, so chi-square is valid: p = 0.0078.

Fisher — small counts

Null — immune share equal in control and tumor. Expected counts — the table that null predicts. p — chance of a table this far off by randomness: 3 in 10,000.

Any expected count below 5, so Fisher: p = 2.91263e-04.

The decision flow

Tip

Write the test name in the figure legend. A reader can then check whether the claim is supported.

⚡ Q1: p2 is right-skewed, p3 is normal. You want to compare them. Which test?

  • A. t-test
  • B. Wilcoxon

✅ B — p2 fails the normal check, so the rank test

  • A the t-test assumes the normal distribution — p2’s p = 1.924505e-09 says it is not normal
  • B Wilcoxon uses ranks and assumes nothing: p = 4.502014e-12 — the gap 17.5 vs 28.07 is real

Check the shape before choosing the test.

⚡ Q2: Both 5-spot groups pass Shapiro-Wilk (p = 0.97 and 0.81). Which test?

  • A. t-test
  • B. Wilcoxon

✅ A — p > 0.05 is no evidence against normal, so the t-test is fair

  • A both groups pass: p = 2.275325e-06 — the gap 28 vs 16.4 is real
  • B the rank test is not needed here, and 5 vs 5 cannot go below p = 0.0079

Five spots cannot prove normal — p > 0.05 means “not rejected”. Say n = 5 in the figure.

⚡ Q3: 30 spots — immune 2 / other 18 in control, immune 8 / other 2 in tumor. Which test?

  • A. chi-square
  • B. Fisher

✅ B — the smallest expected count is 3.33, below 5

  • A R warns Chi-squared approximation may be incorrect — the expected counts 6.67, 13.33, 3.33, 6.67 include a value below 5
  • B Fisher counts the tables exactly: p = 2.91263e-04

Read the expected counts, not the observed counts, to choose.

⚡ Q4: t.test(p4, p2) gives p = 0.164. What does that say?

  • A. p4 and p2 are the same
  • B. no evidence of a difference

✅ B — p is the chance of a gap this big by randomness, not proof of equality

  • gap 3.1 counts
  • sd 6.45 in p4, 1.28 in p2
  • n = 10 vs 30
  • p = 0.164
  • A p > 0.05 does not show the groups are equal — it shows the data is not evidence
  • B a gap of 3.1 against a spread of 6.45 carries little weight; report the gap, the sd, and the test name

Say no evidence, never “no difference”.

✅ Summary

  • p = how surprising the data is, assuming no effect — p > 0.05 = not evidence
  • 20,000 genes → always correct — Bonferroni is strict, BH controls the share of noise
  • the unit is what varies independently — count patients, not spots
  • 2 groups → t / Wilcoxon · paired → paired t / signed-rank · 3+ groups → ANOVA / Kruskal · counting → chi-square (expected ≥ 5) / Fisher (expected < 5)
  • spread decides as much as the gap — name the test in the legend

5. Correlation & Regression

1. Review from Lecture 8

2. Descriptive Statistics

3. Shape, Distribution & Normality

4. p-value & Statistical Tests

5. Correlation & Regression

6. Statistics Practice

7. From Numbers to Figures

8. The Common Plots

9. Reading a ggplot2 Call

10. Export for Publication

11. Graphics Practice

⚠️ The problem: two numbers per spot

Every test so far compares groups — control vs tumor, pre vs post, category vs category.

Some questions have no groups: two measurements on the same spot, and the question is whether they move together.

Pearson — a straight line

r = 0.9994, p = 4.799893e-10 — gene_b tracks gene_a almost perfectly.

  • Pearson: straight-line relationship

Pearson visualization

Spearman — the rank order

rho = 1, p = 4.960317e-05 — every spot keeps its order.

  • Spearman: monotone — “as one goes up, so does the other”

Spearman visualization

The caveat: One hot spot breaks Pearson

Pearson: r = 0.658, p = 0.076 — not significant. Spearman: rho = 1, p = 4.960317e-05 — unchanged.

  • Pearson uses the values — one extreme count pulls the line

  • Spearman uses the ranks — the spot is still the highest, so the ordering is untouched

Correlation is not causation

tumor spots and normal spots can correlate in gene expression without one causing the other.

Both may be driven by a third thing: hypoxia, immune infiltration, tumor content.

Note

Adjacent spots are not independent — they share tissue. A correlation between them can be a neighbourhood effect, not a biological link.

How much does one move when the other rises?

Correlation answers how well the two counts move together — one number, no size.

The next question is how much: the counts gene_b gains when gene_a rises by one. Regression draws the line and reports the slope.

Regression — a line through the data

  • intercept −2.195 — the value at 0 counts, not meaningful here
  • slope 0.9115 — gene_b rises 0.91 counts per gene_a count, p = 4.799893e-10
  • R² 0.9988 — the line explains 99.88% of the variation

Reading a regression

The slope is the claim. The intercept is usually plumbing. The p-value tells you the slope is real; R² tells you the line fits.

✅ Summary

  • Pearson = straight line · Spearman = ranks
  • correlation ≠ causation
  • regression = slope (the claim) + p (the confidence) + R² (the fit)
  • spatial data is not independent — say what the correlation means

6. Statistics Practice

1. Review from Lecture 8

2. Descriptive Statistics

3. Shape, Distribution & Normality

4. p-value & Statistical Tests

5. Correlation & Regression

6. Statistics Practice

7. From Numbers to Figures

8. The Common Plots

9. Reading a ggplot2 Call

10. Export for Publication

11. Graphics Practice

🖥️ Colab Session — Statistics Practice

Same as Lectures 5, 6 and 8: the practice runs in Google Colab, R runtime, nothing to install.

  • Upload counts_annotated.tsv — Lecture 6’s count matrix
  • Open lecture-09_statistics_practice.ipynb, set Runtime → Change runtime type → R
  • Run the cells in order: Runtime → Run All

The notebook takes the deck’s tools to the real matrix: descriptive stats, shape check, per-gene tests, BH correction, correlation and regression.

counts → QC → statistics → figure

The goal is not the p-value. It is explaining your data to another person — and a figure does that faster than any table.

Important

The figure is the deliverable — that is what sections 7-12 are for.

7. From Numbers to Figures

1. Review from Lecture 8

2. Descriptive Statistics

3. Shape, Distribution & Normality

4. p-value & Statistical Tests

5. Correlation & Regression

6. Statistics Practice

7. From Numbers to Figures

8. The Common Plots

9. Reading a ggplot2 Call

10. Export for Publication

11. Graphics Practice

🎬 Previously on statistics…

  • Center & spread: median resists outliers, mean absorbs them; report mean ± sd, keep var for models.
  • Check shape first: shapiro.test() & Q-Q plot decide the test — normal \(\rightarrow\) parametric, skewed \(\rightarrow\) rank test.
  • Test biological units: compare patients, not pooled spots (no pseudoreplication) — \(t\) / ANOVA vs Wilcoxon / Kruskal.
  • Multiple testing: 20,000 genes give \(\sim 1,000\) fluke hits at \(p < 0.05 \rightarrow\) control FDR with Benjamini-Hochberg (BH).
  • Associate & model: Pearson \(r\) (linear) vs Spearman \(\rho\) (ranks); lm() gives the slope and fit (\(R^2\)).

Tip

Statistics tells us something moved — figures show what moved and in which direction.

🧾 We’ve done the statistics… What now?

gene Tumor Control log2FC sd p
MKI67 482.5 3.0 7.33 25.1 7.8e-5
CDKN2A 190.0 2.0 6.57 10.7 9.4e-5
EPCAM 323.8 6.0 5.75 15.5 6.1e-5
KRT19 209.0 4.0 5.71 9.6 5.0e-5
CDH1 151.0 5.0 4.92 8.3 8.7e-5
VIM 262.0 8.0 5.03 11.1 4.2e-5
PTPRC 6.0 214.5 −5.16 0.8 3.6e-5
CD3E 2.6 96.8 −5.22 0.5 2.7e-5
CD8A 1.9 70.0 −5.24 0.3 6.0e-5
GAPDH 997.8 1010.8 −0.02 27.6 1.0

Important

Raw data is meaningless, and statistics on raw data is still raw data.

📊 Draw it — 10 genes, 2 groups, one glance

  • up in tumor — MKI67, CDKN2A, EPCAM, KRT19, CDH1, VIM: 30–54×
  • down in tumor — PTPRC, CD3E, CD8A: 36–38× lower — immune cells leave
  • flat — GAPDH, the housekeeping gene (p = 1.0)

Important

Statistics says something moved. The figure says what moved, and in which direction — a pattern no p-value column can hold. That is why we draw. The how starts here.

🖼️ Every figure is code-generated

The figure you just saw is a file on disk.

⚙️ Five perks of code-generated figures

  • repeatable — rerun the script, the same figure.
  • editable — change the data or one aes(), the figure redraws
  • exact — size, dpi, colours are numbers in code, not a mouse drag
  • batchable — one loop over 20 genes, one style for all 20
  • trackable — code is text, so git sees every change

🧰 Tools you’ll need

  • ggplot2: draws figures from a data frame — dots, lines, bars, tiles
  • dplyr: picks, filters, and summarises columns
  • tidyr: reshapes between wide and long
  • ggridges: ridgeline plots
  • RColorBrewer: colour palettes
  • … depending on what you plan to do…

📖 Ask yourself 3 questions before you draw.

  1. what data? — the first argument
  2. what is drawn? — the geometry: dots, lines, bars, boxes, tiles
  3. what maps where? — which column becomes x, y, colour, size

Tip

You do not have to remember the syntax to read it. Every call states its own data, geometry, and mapping, in that order.

8. The Common Plots

1. Review from Lecture 8

2. Descriptive Statistics

3. Shape, Distribution & Normality

4. p-value & Statistical Tests

5. Correlation & Regression

6. Statistics Practice

7. From Numbers to Figures

8. The Common Plots

9. Reading a ggplot2 Call

10. Export for Publication

11. Graphics Practice

A. General plots

  • scatter, line — relationship and trend
  • bar, box, histogram, density — one column of numbers, and groups
  • dot plot, stacked bars, Venn, UMAP/tSNE, correlation matrix — composition, overlap, and pairs of measures

Note

One slide per plot type: the figure, the question it answers, and the numbers it is built from.

🧾 Base graphics: the four shapes you meet first

  • scatter — does y move with x?
  • line — how does y change across x?
  • boxplot — centre, spread, outliers, per group
  • histogram — how one column is spread

⚪ Scatter and line: relationship and trend

plot(1:5, c(2, 4, 6, 8, 10), type = "b")

  • scatter → relationship: one dot per pair, does y move with x
  • line → trend: the same dots joined in order, the shape is the trend
  • join only what is ordered: spot 1 → 5, time 1 → 12

📊 Bar plots: one value per category

  • bar → one value per category: the height is the value — say which (mean, median, count, sum)
  • The bar hides the spread behind it

Note

Bar plots show one number per group. Ask what the number is: mean, median, count, sum. The caption has to say, and the axis label usually does not.

📊 Bars with error bars: the bar, plus the spread

  • bar + error bar → one value per category, with its spread: bar is the centre, arms are the spread (sd, SE, or CI — say which)
  • Overlapping arms mean the gap is not clean

Note

An error bar is the smallest honest fix for a hidden spread. What it is — sd, standard error, confidence interval — has to be in the caption.

📊 Box plots: centre, spread, and outliers per group

  • box → centre, spread, outliers: one box per group, all on one axis
  • The box keeps the spread visible, per group

Note

Read the axis before the shape. A boxplot of UMI and a boxplot of p-values look the same and mean nothing alike.

📊 Histograms: how one column is spread

  • histogram → spread of one column: binned — the bars are counts, not values
  • The shape shows where the mass sits

Note

A histogram has one axis that is not the data: the y-axis is the bin count. Change breaks and the shape changes — the data did not.

📈 Density and ridgeline: the shape, without bins

  • density / ridgeline → shape without bins: smoothed curve of one column; stacked when per group
  • The curve shows where the mass sits, not just the centre

Note

A histogram depends on breaks, a density on the bandwidth. Both are choices about the picture, not properties of the data.

⚪ Dot plot: every spot, one dot

  • dot plot → every value, one dot: one dot per observation, no bins
  • Works for tens of points; at thousands the dots blur into a curve

Note

A dot plot is a histogram that refuses to bin. It works for tens of points; at thousands the pile becomes a curve.

📊 Stacked bars: composition inside one bar

  • stacked bar → composition inside one bar: one bar split by group; 100% stacked shows shares
  • Read both how tall the bar is and how the inside is split

Note

Stacked bars show composition. Read two things: how tall the bar is, and how the inside is split. A tall bar and a large share are different claims.

🧇 Venn diagram: how much two sets share

  • Venn → how much two or three sets share: each region is a count of genes
  • Two sets are readable; three are the limit

Note

A Venn answers “how much is shared”. Two sets are readable; three are the limit, and four sets stop being a picture of the counts.

🧬 UMAP / tSNE: cells flattened to a plane

  • UMAP / tSNE → cells flattened to a plane: one dot per cell; position is learned similarity, colour is the label
  • Far apart means different expression profiles — not far apart in the tissue

Note

UMAP and tSNE are dimension reduction: neighbourhood, not geography. A spot map keeps the real x and y; a UMAP does not.

🧮 Correlation matrix: r for every pair

  • correlation matrix → r for every pair: one cell per pair of genes, value is r
  • Read sign and size together; the diagonal is 1.00 by definition

Note

Read sign and size together. The colours are a palette choice; the numbers are the claim, so read the matrix with the values in it.

B. Spatial & DE plots

  • spot map — real x, y in tissue, colour = expression
  • violin — the whole distribution, per sample
  • volcano — one dot per gene: effect size against significance
  • heatmap — gene × sample as coloured cells

Note

The same shapes, on data that carries a gene name, a sample name, or a position in the tissue.

🗺️ Spot map: expression on a tissue

ggplot(spots, aes(x = x, y = y)) + geom_point(aes(colour = expr)) + coord_equal()
  • spot map → expression on a tissue: one dot per spot; x, y are positions, colour is expression
  • The map keeps real x, y in the tissue

Note

coord_equal() makes 1 unit of x the same length as 1 unit of y, so a round tissue stays round.

🎻 Violin: the whole distribution, per group

ggplot(umi, aes(x = sample, y = umi, fill = sample)) +
  geom_violin(trim = FALSE) + geom_boxplot(width = 0.12) + scale_y_log10()
  • violin → whole distribution, per group: mirrored density; width is how many sit at that value
  • The box inside is the boxplot, drawn inside the curve

Note

A violin is a mirrored density. The box inside it is the boxplot from the box slide, drawn inside the curve.

🌋 Volcano: effect size against significance

ggplot(de, aes(x = log2FC, y = -log10(padj), colour = state)) +
  geom_point() + geom_hline(yintercept = -log10(0.05), linetype = "dashed") +
  geom_vline(xintercept = c(-1, 1), linetype = "dashed")
  • volcano → effect size against significance: one dot per gene; x is effect, y is −log10(FDR)
  • The dashed lines are the thresholds the authors chose

Note

A volcano has thresholds drawn on it. The dashed lines are the cut the authors chose, not a property of the data.

🟥 Heatmap: one cell per gene × sample

ggplot(heat, aes(x = sample, y = gene, fill = value)) +
  geom_tile() +
  scale_fill_distiller(palette = "YlOrRd")
  • heatmap → one cell per gene × sample: colour is the value
  • Read the colour scale bar with the matrix

Note

A heatmap is a table painted on. One linear map turns values into colour, so the scale bar carries all the numbers.

⚡ Q1: Control vs tumor UMI — you want centre, spread, outliers per group. Which plot?

  • A. bar
  • B. box plot
  • C. scatter
  • D. histogram

✅ B — box plot

  • A one bar per group; the spread behind it is hidden.
  • B one box per group: centre, spread, outliers on one axis.
  • C needs two numbers per spot; here there are groups only.
  • D bins one column; it does not separate groups.

One box per group, all on one axis.

⚡ Q2: 2000 genes, log2FC + FDR per gene. Which plot?

  • A. volcano
  • B. heatmap
  • C. violin
  • D. stacked bar

✅ A — volcano

ggplot(de, aes(x = log2FC, y = -log10(padj))) + geom_point()
  • A x is effect, y is significance — the two columns you have.
  • B needs genes by samples; here there are no samples.
  • C needs one value per group; here there are 2000 genes.
  • D shows shares in one bar; here there is no share.

One dot per gene.

⚡ Q3: Expression values for genes by samples. Which plot?

  • A. volcano
  • B. violin
  • C. heatmap
  • D. Venn

✅ C — heatmap

ggplot(heat, aes(x = sample, y = gene, fill = value)) +
  geom_tile()
  • A needs log2FC and FDR; here there is one value per pair.
  • B shows one distribution per group; here there are genes by samples.
  • C one cell per (gene, sample); colour is the value.
  • D shows shared counts between sets; here there are no sets.

Read the scale bar with the matrix.

9. Reading a ggplot2 Call

1. Review from Lecture 8

2. Descriptive Statistics

3. Shape, Distribution & Normality

4. p-value & Statistical Tests

5. Correlation & Regression

6. Statistics Practice

7. From Numbers to Figures

8. The Common Plots

9. Reading a ggplot2 Call

10. Export for Publication

11. Graphics Practice

🧱 The problem: long — one row per gene × sample

long <- data.frame(
  gene = rep(c("MKI67", "CDKN2A", "EPCAM"), each = 3),
  sample = rep(c("Tumor", "Adjacent", "Control"), 3),
  tpm = c(58, 12, 4, 31, 9, 2, 44, 17, 6)
)
  • ggplot2 needs long data: one row per gene × sample, one column per variable. 3 genes × 3 samples = 9 rows.

🧱 Load the lib: ggplot2 + colours

library(ggplot2)

cols <- c(Tumor = "red", Adjacent = "orange", Control = "blue")
  • library(ggplot2) loads the grammar; cols names one colour per sample for later.

🧱 ggplot(long, aes(...)) — data and mapping, no drawing yet

# run the two slides above first (long, ggplot2)
ggplot(long, aes(x = sample, y = tpm, fill = sample))
  • ggplot() names the data; aes() says which column is x, y, colour. No picture yet.

🧱 Step 2: + geom_col() — the bars

# run the steps above first (long, ggplot2, cols)
ggplot(long, aes(x = sample, y = tpm, fill = sample)) +
  geom_col()
  • geom_* is what is drawn: bars, height is tpm.

🧱 Step 3: + facet_wrap() — one panel per gene

ggplot(long, aes(x = sample, y = tpm, fill = sample)) +
  geom_col() +
  facet_wrap(~ gene, scales = "free_y")
  • Each panel is one gene; free_y gives each panel its own y-axis.

🧱 Step 4: + scale_fill_manual() — the colours

ggplot(long, aes(x = sample, y = tpm, fill = sample)) +
  geom_col() +
  facet_wrap(~ gene, scales = "free_y") +
  scale_fill_manual(values = cols)
  • scale_* sets the colour range; here the three sample colours.

🧱 Step 5: + coord_cartesian() — the axis limits

ggplot(long, aes(x = sample, y = tpm, fill = sample)) +
  geom_col() +
  facet_wrap(~ gene, scales = "free_y") +
  scale_fill_manual(values = cols) +
  coord_cartesian(ylim = c(0, 60))
  • Fixes the y-axis to 0–60, so panels start at the same base.

🧱 Step 6: + labs() — the labels

ggplot(long, aes(x = sample, y = tpm, fill = sample)) +
  geom_col() +
  facet_wrap(~ gene, scales = "free_y") +
  scale_fill_manual(values = cols) +
  coord_cartesian(ylim = c(0, 60)) +
  labs(title = "TPM", x = NULL)
  • Adds the title; no more x-label.

🧱 Step 7: + theme_minimal() — the whole call

ggplot(long, aes(x = sample, y = tpm, fill = sample)) +
  geom_col() +
  facet_wrap(~ gene, scales = "free_y") +
  scale_fill_manual(values = cols) +
  coord_cartesian(ylim = c(0, 60)) +
  labs(title = "TPM", x = NULL) +
  theme_minimal()
  • Styling only. Data, geometry, and mapping are the first three steps.

🔀 Long data: the shape ggplot2 needs

Wide — 3 rows, 3 gene columns

sample MKI67 CDKN2A EPCAM
Tumor 58 31 44
Adjacent 12 9 17
Control 4 2 6

Long — 9 rows, 3 columns

gene sample tpm
MKI67 Tumor 58
MKI67 Adjacent 12
MKI67 Control 4
CDKN2A Tumor 31
… … …
tidyr::pivot_longer(wide, cols = -sample,
                    names_to = "gene", values_to = "tpm")
# 3 gene columns become one gene column and one value column, 9 rows

aes() maps columns. One column of gene names is what facet_wrap splits on, and one column of values is what every gene shares.

👁️ Envision the plot first

  • Name the plot before you code it: data, geometry, mapping.
  • Describe the vision in words — let AI draft the ggplot2 call.
  • Read each line against your vision, run it, adjust.

Understanding the code matters because AI writes layers for you.

10. Export for Publication

1. Review from Lecture 8

2. Descriptive Statistics

3. Shape, Distribution & Normality

4. p-value & Statistical Tests

5. Correlation & Regression

6. Statistics Practice

7. From Numbers to Figures

8. The Common Plots

9. Reading a ggplot2 Call

10. Export for Publication

11. Graphics Practice

💾 The problem: a figure on screen is not a file

  • What you see in R is temporary. Journals, slides, and collaborators need a saved file.

💾 ggsave() writes it

ggsave("volcano.pdf", p_vol, width = 5.4, height = 3.4)
  • One line: the file, the plot object, the print size in inches.

💾 Why both PDF and PNG?

ggsave("volcano.pdf", p_vol, width = 5.4, height = 3.4)
ggsave("volcano_300.png", p_vol, width = 5.4, height = 3.4, dpi = 300)
  • PDF — vector: edit in Illustrator, lossless for publication.
  • PNG — pixels: easy preview everywhere; 300 dpi for print, 72 dpi for screen.

✅ Before a figure leaves your laptop

  • The figure is sized for print (5.4 in), not for the screen
  • Every axis label carries units; every panel has a letter (A, B, C)
  • The legend states the test and the threshold: “FDR < 0.05, |log2FC| > 1”
  • The palette is colourblind-safe, not red/green only
  • The code and the data table behind each figure must be saved together
  • Journals ask 300 dpi for photos, heatmaps, and spots; vector for line art

Important

A figure is a claim. If you cannot rebuild it from the code, you cannot defend it.

11. Graphics Practice

1. Review from Lecture 8

2. Descriptive Statistics

3. Shape, Distribution & Normality

4. p-value & Statistical Tests

5. Correlation & Regression

6. Statistics Practice

7. From Numbers to Figures

8. The Common Plots

9. Reading a ggplot2 Call

10. Export for Publication

11. Graphics Practice

🖥️ Graphics Practice — in the notebook

The practice moved to lecture-09_r_statistics_graphics_practice.ipynb:

  • Volcano — PC9 Apatinib: effect vs BH p, 2 hits.
  • Heatmap — top 6 genes × PC9 samples.

Open the notebook and Run All — real matrix, no mock figures.

🧠 Recap

  • the verb names the job: geom_* draws, scale_* ranges, coord_* shape, facet_* panels
  • read a call in 3 questions: data, geometry, mapping — envision first, draft with AI, read the code
  • the shapes: scatter, line, bar, box, histogram, density, Venn, UMAP, then volcano, heatmap, violin, spot map
  • export: PDF for publication (vector), PNG for preview (300 dpi)

🚀 What’s Next?

Lecture 10 — Version Control, Environments & Good Coding Practices

  • the same reproducible habits: Git checkpoints, a numbered project, and clean code
  • Colab + environment.yml so the exact toolbox rebuilds anywhere.

📚 Sources & Licenses

  • R Core Team, R 4.5.3 — base stats: mean, median, sd, quantile, summary, t.test, wilcox.test, kruskal.test, aov, chisq.test, fisher.test, shapiro.test, cor.test, lm, p.adjust, qqnorm, qqline
  • Shapiro & Wilk (1965) Biometrika 52:591-611 · Benjamini & Hochberg (1995) JRSS-B 57:285-307
  • Wickham, H. ggplot2 4.0.3 — ggplot, aes, geom_*, scale_*, facet_wrap, coord_equal, ggsave; with dplyr, tidyr (pivot_longer), ggridges, RColorBrewer
  • every figure and number in this deck is drawn in the course’s R_tutorial env (R 4.5.3, ggplot2 4.0.3, ggridges 0.5.7) on png() / pdf() devices, fixed seed
  • Course data: GSE129221 — Song et al. (2019) Cancer Cell Int 19:117
  • p-value meme (section 4) — FB: @Statisticss · IG: @StatisticsForYou; image via Google Images: encrypted-tbn0.gstatic.com
  • Gulls on a bent railing (section 5, “Correlation is not causation”) — photo via X: pbs.twimg.com/media/FAW2hMeWEAAfcvm
  • Deck: Quarto 1.10.19 · revealjs · slides.css

Thank You!

A reviewer sees your figures before your statistics.

Make both tell the same true story.