install.packages("readr")
install.packages("dplyr")
install.packages("ggplot2")9 Data visualization with ggplot2
In this lesson, you’ll make the basic plots in R with ggplot2. Data visualization is for communicating your ideas.
If you read genomics papers, most figures fall into six types:
A bar plot
A line plot
A scatter plot
A boxplot or violin plot
A histogram
A heatmap
If you master those six types, you can make most of the figures you see in genomics papers. Watch this:
ggplot2 builds a plot in layers:
The data layer - the data frame you want to plot
The aesthetic mapping - how data columns map to visual properties like x/y position, color, size etc.
Geometric objects like points, lines, boxes - the type of plot
Facets - panels for subgrouping the data
Stats transformations like group means, regressions etc.
Themes to refine the final look
Let’s walk through examples of common plot types.
9.1 Creating Scatter Plots
We’ll use the TCGA gene expression data and ask one question: do EPCAM and CEACAM5 go up together across 10,000 tumors? On the way, you’ll make a scatter plot, calculate a correlation, test it, and add a regression line.
9.1.1 Prerequisites
You need three packages: readr, dplyr and ggplot2. Install them once if you haven’t already:
We use the same TCGA gene expression data (a CSV file) as in the previous lessons. The code below reads it straight from the course data server, so it works on any computer and in the Codespace with nothing to download. If you prefer a local copy, download the file from https://osf.io/yeun5 into your project folder and use the commented line instead.
9.1.2 Loading and Exploring the Data
Read the table with read_csv() from the readr package:
library(readr)
library(dplyr)
# Load the TCGA gene expression data (straight from the web, no download needed)
tcga_data <- read_csv("https://learn.chatomics.com/data/r-course/TCGA_cancer_genes_expression.csv")
# or, from a copy in your project folder:
# tcga_data <- read_csv("TCGA_cancer_genes_expression.csv")Look at the first few rows:
head(tcga_data)# A tibble: 6 × 25
...1 TACSTD2 VTCN1 MUC1 NECTIN4 FOLH1 FOLR1 CD276 MSLN CLDN6 ERBB2
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 43e715bf… 0.704 0 0.675 0.0862 7.21 0 52.8 0.0667 0.0970 1.88
2 1a5db9fc… 25.4 0 2.02 0.0728 23.6 0.122 78.8 0.956 0.255 7.78
3 93b382e4… 1.58 0 0.908 0.699 2.85 1.01 146. 0.0456 0.257 2.91
4 1f39dadd… 0.270 0.0910 0.0429 0.0165 1.16 0.279 48.5 0.0315 0.247 4.91
5 8c8c09b9… 0.412 0 0.115 0.0317 2.41 0.0492 42.3 0.270 0.126 1.49
6 85a86b91… 4.55 4.86 0.0421 0.0683 1.01 0.0225 20.6 0.0134 0.0182 13.5
# ℹ 14 more variables: MUC16 <dbl>, DLL3 <dbl>, CEACAM5 <dbl>, PVR <dbl>,
# EPCAM <dbl>, PROM1 <dbl>, CD24 <dbl>, EGFR <dbl>, MET <dbl>,
# TNFRSF10B <dbl>, tcga.tcga_barcode <chr>,
# tcga.cgc_sample_sample_type <chr>, study <chr>, sample_type <chr>
Each row is one sample. The gene columns hold expression values, and the last columns tell you the study (cancer type) and the sample type: cancer, metastatic or normal.
9.1.3 Filtering the Data
We only want the tumors, so we drop the normal and metastatic samples:
table(tcga_data$sample_type)
cancer metastatic normal
10021 394 740
# Filter the data to include only cancer samples
tcga_cancer <- tcga_data %>%
filter(sample_type == "cancer")%>% passes the table to filter(), which keeps the rows where sample_type is “cancer”.
9.1.4 Creating a Scatter Plot
For docs check: https://ggplot2.tidyverse.org/reference/ggplot.html
Put EPCAM on the x-axis and CEACAM5 (CEA) on the y-axis.
Docs on geom_point: https://ggplot2.tidyverse.org/reference/geom_point.html
library(ggplot2)
# Create a scatter plot
ggplot(tcga_cancer, aes(x = EPCAM, y = CEACAM5)) +
geom_point()
ggplot() takes the data, aes() maps EPCAM to x and CEACAM5 to y, and geom_point() draws one point per sample.
9.1.4.1 Interpretation
Each point is a tumor. If the points rise together from bottom-left to top-right, the two genes go up together.
9.1.5 Calculating Correlation
To put a number on it, calculate the Pearson correlation coefficient. It measures the strength and direction of a linear relationship between two variables.
# Calculate the Pearson correlation coefficient
correlation <- cor(tcga_cancer$EPCAM, tcga_cancer$CEACAM5)
correlation[1] 0.6324328
The output is a value between -1 and 1, where:

A positive value (closer to 1) indicates a positive correlation (both variables increase together).
A negative value (closer to -1) indicates a negative correlation (one variable increases as the other decreases).
A value close to 0 indicates little to no linear correlation.
Here Pearson’s r is 0.63, a moderate positive correlation.
Now look at the scatter plot again. Most tumors sit in the bottom-left corner, and the rest fan out far to the right and the top. Pearson’s r is pulled by those big values. Two quick checks:
# Spearman uses the ranks, so a few huge values can't dominate
cor(tcga_cancer$EPCAM, tcga_cancer$CEACAM5, method = "spearman")[1] 0.5621122
# Pearson on the log scale
cor(log2(tcga_cancer$EPCAM + 1), log2(tcga_cancer$CEACAM5 + 1))[1] 0.4860239
Same direction, smaller numbers: 0.56 and 0.49. Expression values are skewed like this, so log-transform them first or use Spearman.
9.1.6 Hypothesis Testing
Check docs here: https://rdrr.io/r/stats/cor.test.html
Is this correlation significantly different from zero? Test it:
# Perform a correlation hypothesis test
cor_test_result <- cor.test(tcga_cancer$EPCAM, tcga_cancer$CEACAM5)
cor_test_result
Pearson's product-moment correlation
data: tcga_cancer$EPCAM and tcga_cancer$CEACAM5
t = 81.722, df = 10019, p-value < 2.2e-16
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
0.6205372 0.6440374
sample estimates:
cor
0.6324328
9.1.6.1 Interpretation
In the results, you’ll see:
The t-value, which measures the number of standard errors the correlation coefficient is away from zero.
The degrees of freedom (df), which are related to the sample size.
The p-value, which tells us whether the correlation is statistically significant.
The p-value is very close to zero (p-value < 2.2e-16): strong evidence against the null hypothesis that the true correlation is zero. But keep in mind that in genomics data analysis you often have thousands of samples, and you will get tiny p-values for even weak correlations. So look at the size of the correlation (0.63 here, 0.49 on the log scale), not the p-value.
9.1.7 Adding a Regression Line
Check docs on geom_smooth here: https://ggplot2.tidyverse.org/reference/geom_smooth.html
Add a linear regression line with geom_smooth():
# Create a scatter plot with a regression line
ggplot(tcga_cancer, aes(x = EPCAM, y = CEACAM5)) +
geom_point() +
geom_smooth(method = "lm")
method = "lm" fits a straight line through the points. The line shows how CEACAM5 changes as EPCAM goes up. An upward slope means a positive correlation; a downward slope, a negative one.
And remember: correlation does not imply causation. Two genes can go up together without one controlling the other.
9.2 Understanding Distributions with Histograms
A histogram shows the distribution of one numeric variable. We keep using the tcga_cancer table we made above.
9.2.1 Creating a Basic Histogram
Here is the distribution of EPCAM expression across all cancer samples:
# Create a basic histogram for EPCAM gene expression
ggplot(tcga_cancer, aes(x = EPCAM)) +
geom_histogram()
Map EPCAM to the x-axis and add geom_histogram(). The y-axis is the count of samples in each “bin”. A bin is a range of values, and the height of each bar is how many samples have expression in that range.
9.2.2 Customizing Histogram Bins
You can change the number of bins. More bins show more detail; fewer bins give you a broader view.
9.2.2.1 Changing the Number of Bins
Use the bins argument of geom_histogram():
# Create a histogram with 50 bins
ggplot(tcga_cancer, aes(x = EPCAM)) +
geom_histogram(bins = 50)
9.2.2.2 Customizing Bin Borders
By default, the borders of the bins are hard to see. Make them white:
# Create a histogram with white bin borders
ggplot(tcga_cancer, aes(x = EPCAM)) +
geom_histogram(bins = 50, color = "white")
Now you can tell the bars apart.
9.3 Visualizing Data Distribution with Boxplots and Violin Plots
A boxplot shows the median, the quartiles and the outliers of each group, so you can compare all the cancer types in one picture. We continue with the cancer samples in tcga_cancer.
9.3.1 Creating a Basic Boxplot
EPCAM expression by cancer type:
library(ggplot2)
ggplot(tcga_cancer, aes(x = study, y = EPCAM)) +
geom_boxplot()
study (the cancer type) goes on the x-axis, EPCAM on the y-axis, and geom_boxplot() draws one box per cancer type.
9.3.2 Rotating X-axis Labels
The x-axis labels (cancer types) overlap. Rotate them by 90 degrees and remove the x-axis title with theme():
ggplot(tcga_cancer, aes(x = study, y = EPCAM)) +
geom_boxplot() +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
axis.title.x = element_blank())
Now the x-axis labels are readable.
9.3.3 Adding Color to Boxplots
To tell the cancer types apart, map the color aesthetic to the study:
ggplot(tcga_cancer, aes(x = study, y = EPCAM)) +
geom_boxplot(aes(color = study)) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
axis.title.x = element_blank())
Or use fill to color the boxes instead of the outlines:
ggplot(tcga_cancer, aes(x = study, y = EPCAM)) +
geom_boxplot(aes(fill = study)) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
axis.title.x = element_blank())
ggplot2 uses its default color palette, but you can set the colors yourself.
9.3.4 Customizing Color Palettes
To define your own color palette for the cancer types, use the Polychrome package. First, how many cancer types are there?
# how many cancer types?
length(unique(tcga_cancer$study))[1] 32
32, not 33. TCGA has 33 cancer types, and LAML (acute myeloid leukemia) is missing here because of a bug in how I built this table. Lesson 10 shows the bug and how to catch it.
Here’s how to create a custom color palette for 32 cancer types:
# install.packages("Polychrome")
library(Polychrome)
# 32 cancer types
length(unique(tcga_cancer$study))[1] 32
# Create a custom color palette with Polychrome
P32 <- createPalette(32, c("#FF0000", "#00FF00", "#0000FF"), range = c(30, 80))
P32 NC1 NC2 NC3 NC4 NC5 NC6 NC7 NC8
"#F90D00" "#26E51C" "#0022F7" "#EFB7C0" "#FD1CEA" "#0DD6FE" "#CBC200" "#F38622"
NC9 NC10 NC11 NC12 NC13 NC14 NC15 NC16
"#226E45" "#D8227A" "#6E2288" "#6C4B00" "#C30DFF" "#8699F7" "#7588A4" "#FE86D9"
NC17 NC18 NC19 NC20 NC21 NC22 NC23 NC24
"#1CE19E" "#882E4F" "#C0C491" "#6CAD26" "#CA2E1C" "#DE89FF" "#EFB375" "#FC8A94"
NC25 NC26 NC27 NC28 NC29 NC30 NC31 NC32
"#6CD3C9" "#E3B6F1" "#984200" "#F200B4" "#7D3BCA" "#694B56" "#004987" "#95007A"
You see the hex code for the colors.
P32 holds 32 distinct colors. Look at them with swatch(P32) from the Polychrome package:
swatch(P32)
9.3.5 Applying Custom Color Palette
To use the palette in the boxplot, map the colors to the study with scale_fill_manual() (or scale_color_manual() for outlines):
ggplot(tcga_cancer, aes(x = study, y = EPCAM)) +
geom_boxplot(aes(fill = study)) +
scale_fill_manual(values = unname(P32)) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
axis.title.x = element_blank())
Note, you need to remove the names of the named color vector using unname.
9.3.6 Reordering Boxplots
To order the boxes by the median EPCAM expression, use forcats::fct_reorder() inside aes():
ggplot(tcga_cancer, aes(x = study %>%
forcats::fct_reorder(EPCAM, median),
y = EPCAM)) +
geom_boxplot(aes(fill = study)) +
scale_fill_manual(values = unname(P32)) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
axis.title.x = element_blank())
forcats::fct_reorder() takes two arguments:
The first argument (study) is the factor variable whose levels we want to reorder.
The second argument (EPCAM) is the numeric variable based on which the reordering will be done (in this case, the median expression levels of EPCAM).
The levels of study are now ordered from low to high median EPCAM, so the boxes are too.
9.3.7 Using Violin Plots
A violin plot draws the density of the data, mirrored, so you see the whole shape of the distribution, including two humps that a boxplot would hide. geom_violin() draws no median and no box. Add geom_boxplot(width = 0.1, outlier.shape = NA) on top if you want them.
ggplot(tcga_cancer, aes(x = study %>%
forcats::fct_reorder(EPCAM, median),
y = EPCAM)) +
geom_violin(aes(fill = study), scale = "width") +
scale_fill_manual(values = unname(P32)) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
axis.title.x = element_blank())
We replaced geom_boxplot with geom_violin. scale = "width" gives every violin the same width, so the thin ones are still visible.
9.4 Creating Bar Plots to Visualize Median EPCAM Levels by Cancer Type
A bar plot of the median EPCAM in each cancer type. First calculate the medians, then plot them, then sort the bars.
9.4.1 Calculating Median EPCAM Levels by Cancer Type
One row per cancer type, with its median EPCAM:
# Calculate median EPCAM levels by cancer type
EPCAM_median <- tcga_cancer %>%
group_by(study) %>%
summarize(median_EPCAM = median(EPCAM))
# Display the summary table
EPCAM_median# A tibble: 32 × 2
study median_EPCAM
<chr> <dbl>
1 ACC 4.83
2 BLCA 81.1
3 BRCA 162.
4 CESC 75.9
5 CHOL 251.
6 COAD 778.
7 DLBC 0.578
8 ESCA 189.
9 GBM 0.307
10 HNSC 24.7
# ℹ 22 more rows
9.4.2 Creating a Basic Bar Plot
Now plot the medians with geom_bar():
library(ggplot2)
# Create a basic bar plot
ggplot(EPCAM_median, aes(x = study, y = median_EPCAM)) +
geom_bar(stat = "identity") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
axis.title.x = element_blank())
geom_bar(stat = "identity") makes the height of each bar the median EPCAM value, and theme() rotates the x-axis labels as before.
The bars are in alphabetical order, not ordered by value. Let’s fix that.
9.4.3 Reordering the Bars
Use forcats::fct_reorder() again, this time on median_EPCAM:
# Reorder the bars based on median EPCAM values
ggplot(EPCAM_median, aes(x = study %>%
forcats::fct_reorder(median_EPCAM),
y = median_EPCAM)) +
geom_bar(stat = "identity") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
axis.title.x = element_blank())
The bars now go from the lowest to the highest median EPCAM, and you can see at a glance which cancer types have the most.
9.4.4 Reversing the Order
To reverse the order of the bars, add .desc = TRUE to forcats::fct_reorder():
# Reverse the order of the bars
ggplot(EPCAM_median, aes(x = study %>%
forcats::fct_reorder(median_EPCAM, .desc = TRUE),
y = median_EPCAM)) +
geom_bar(stat = "identity") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
axis.title.x = element_blank())
With .desc = TRUE, the bars go from the highest to the lowest median EPCAM.
9.4.5 Note on factor levels
ggplot2 orders a categorical axis by the factor levels of the column, and for a plain character column the default order is alphabetical, which is rarely the order you want. Convert the column to a factor and set the levels explicitly, or use the forcats helpers: fct_reorder() orders levels by a statistic, fct_relevel() moves specific levels to the front, and fct_rev() flips the order. Set the levels once in the data before plotting, and every geom, facet, and legend will follow the same order.
library(forcats)
df <- data.frame(group = c("tumor", "normal", "metastasis"), value = c(5, 2, 8))
df$group <- fct_reorder(df$group, df$value) # order levels by value
levels(df$group)[1] "normal" "tumor" "metastasis"