Repository navigation
Expand file tree
/
Copy path05_heatmaps.Rmd
More file actions
349 lines (275 loc) · 13.5 KB
/
Copy path05_heatmaps.Rmd
File metadata and controls
349 lines (275 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
---
title: "05_heatmaps"
author: "JR"
date: "2024-08-13"
output: html_document
editor_options:
chunk_output_type: console
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(reshape)
library(tidyr)
library(tibble)
library(ggplot2)
library(dplyr)
library(pheatmap)
library(readr)
source("../../util/plot_theme.R")
```
# Youtube video for this class:
https://youtu.be/sqMQYp0mqnQ
# Goal create "heatmaps"to represent gene abundance across time and replicates.
Heatmaps are a very common and powerful way to represent RNAseq data. It shows the
abundance of each gene, across all samples and shades them in colore
for more or less abundant expression (e.g., red high, blue low). Moreover, a heatmap can
be combined with a "clustering" algorithm to organize the patterns in the data. Finally,
this also tells you how related samples are. We can do this in two steps:
# (1) cluster our samples to find the relationship across samples
# (2) cluster and overlay heatmap of gene abundance across time of dox exposure
Let's get started with "clustering our samples"
First let's load the data
```{r Loading data}
# load TPM RESULTS:
load("/scratch/Shares/rinnclass/MASTER_CLASS/lessons/06_Differential_expression_analyses/results/TPM_results/TPM_results.Rdata")
# laod DESEQ2 results
load("/scratch/Shares/rinnclass/MASTER_CLASS/lessons/06_Differential_expression_analyses/results/counts_results_DESEQ/DESEQ_results.rdata")
```
# (1) Cluster samples
First step is calculating distance between all samples. Let's start with our
TPM data as these are the values typically used for clustering and heatmaps.
# Note use of transmute (t)
# Note log TPM values being used
```{r distance calculation}
# Log-transform the TPM values.
# This helps deflate spurious and low values - common practice for clustering/heatmaps
log_tpm_matrix <- log2(TPM_filtered + 1)
# Now let's calculate how closely related each sample (time point) is to each other using DIST function.
# We make a vector the length of genes in TPM_filtered. Then use correlation (DIST function) to find similarity.
# For other methods check out dist menu
?dist
# Let's start with euclidean distance / similarity based on log2 TPM values of genes in TPM_filtered.
distance_matrix <- dist(t(log_tpm_matrix), method = "euclidean")
# Now we use the function : HCLUST !
# This performs the hierarchical clustering of each samples relationship
?hclust
# Other forms of clustering as well see menu above for now ward or complete
# Downside of ward is it assumes a circle relationship where as complete is linear - like we have with time.
hc_complete <- hclust(distance_matrix, method = "complete")
# Now we can use plot() to plot the distance calucalated in hclust!
plot(hc_complete, labels = colnames(log_tpm_matrix), main = "Global TPM Filtered Dendrogram ", sub = "sample relationship by time and replicate after dox treatment")
# Cool we see that samples see to return closer to 0 after 96 hours of dox treatment
# Also that the replicates are more similar than time points - a very good / expected thing
# Cut tree to limit the clusters
clusters <- cutree(hc_complete, k = 5)
# Print out which sample is in which cluster
print(clusters)
# Cool we can see each time point is represented in each cluster !
```
# Supervised ordering of dendogram
Above we let the distances set where the samples end up.
However we can force it to order the samples the way we want
Strategy: make a dendrogram and then reorder it
# Let's order the samples and see how things change
```{r ordered dendrogram}
# Making a dendrogram of hc_complete
dend_hc_complete <- as.dendrogram(hc_complete)
view(dend_hc_complete)
# Reorder the dendrogram based on the clusters created above
dend_hc_complete <- reorder(dend_hc_complete, clusters)
# Plot the reordered dendrogram
plot(dend_hc_complete, main = "Global TPM Filtered Dendrogram (Ordered by Cluster)", sub = "Sample relationship by time and replicate after dox treatment")
# Voila they are ordered now - not still takes into consideration similarity when ordering !
```
# RESULT: Time points 0,12,96 more similar than 24, 48
# Intrepretation: this could mean most changes occur at 24-48 hours.
# (2) Overlapy a heatmap to measure sample similarity and gene changes across time
# PHEATMAP is a great program for making heat maps it will do
```{r Create Heat map of all filtered TPM genes across all time points and replicates}
# THIS TAKES 3 MIN - but worth it
pheatmap(log_tpm_matrix,
cluster_rows = TRUE, # Cluster genes (rows)
cluster_cols = TRUE, # Cluster samples (columns)
scale = "row", # Scale the data across rows (genes) for better visualization
show_rownames = FALSE, # Hide gene names for clarity
show_colnames = TRUE, # Show sample names
main = "Heatmap of Log2-Transformed TPM Values for Sig genes")
# Notice we just said cluster in the pheatmap commands above
# We can also change them based on what is available in pheatmap
# Let's make a "mini function" to cluster the way we want in pheatmap
custom_dist <- function(x) dist(x, method = "manhattan") # Replace "manhattan" with your preferred method
custom_hclust <- function(x) hclust(x, method = "ward.D2") # Replace "ward.D2" with your preferred clustering method
# Create a heatmap with custom distance and clustering functions
pheatmap(log_tpm_matrix,
cluster_rows = TRUE,
cluster_cols = TRUE,
scale = "row",
show_rownames = FALSE,
show_colnames = TRUE,
main = "Heatmap of Log2-Transformed TPM Values",
color = colorRampPalette(c("blue", "white", "red"))(50),
distfun = custom_dist,
hclustfun = custom_hclust
)
# Note clustering is just a relative pecie of information and not an exact science.
# There is a whole article on the "art of clustering" :)
# More on this here:
# https://proceedings.mlr.press/v27/luxburg12a/luxburg12a.pdf
```
# Let's filter to sig genes and make dendrogram based on them and heatmap
```{r dendrogram and heatmap of significant genes}
# First filter to sig genes object log_tpm_matrix
sig_log_tpm_matrix <- log_tpm_matrix[rownames(log_tpm_matrix) %in% unique_sig_genes, ]
# calculate distances
sig_distance_matrix <- dist(t(sig_log_tpm_matrix), method = "euclidean")
# cluster
hc_sig_distance_matrix <- hclust(sig_distance_matrix, method = "complete")
# Plotting
plot(hc_sig_distance_matrix, labels = colnames(hc_sig_distance_matrix), main = "Log2 TPM Sig Genes Dendrogram ", sub = "sample relationship by time and replicate after dox treatment for sig genes")
# Setting custom clustering and dist funcitons
custom_dist <- function(x) dist(x, method = "manhattan")
custom_hclust <- function(x) hclust(x, method = "ward.D2")
# Create a heatmap for sig genes using custom clust/dist (and change the color)
pheatmap(sig_log_tpm_matrix,
cluster_rows = TRUE,
cluster_cols = TRUE,
scale = "row",
show_rownames = FALSE,
show_colnames = TRUE,
main = "Heatmap of Log2-Transformed TPM Values",
distfun = custom_dist,
color = colorRampPalette(c("blue", "white", "red"))(50),
hclustfun = custom_hclust
)
```
# Now let's change the scale of "heat" to 2,-2
This will turn up the heat :)
```{r changing scale in pheatmap}
# Set the scale
breaks <- seq(-2, 2, length.out = 51)
# Create the heatmap with specified scale limits
pheatmap(sig_log_tpm_matrix,
cluster_rows = TRUE,
cluster_cols = TRUE,
scale = "row",
show_rownames = FALSE,
show_colnames = TRUE,
color = colorRampPalette(c("blue", "white", "red"))(50), # Apply the custom color palette
breaks = breaks, # Apply the breaks to limit the scale
main = "Heatmap of Log2-Transformed TPM Values for Sig genes")
```
# RESULT: Samples mostly cluster as expected except 24_R3
# Now you can make a figure for any gene of interest !!
# RLOG Counts
DESEQ2 does a great funciton of normalizing counts for a heatmap.
This is called rlog counts. There is a bunch of information here:
https://compbiocore.github.io/deseq-workshop-1/assets/deseq_workshop_1.html
Let's do this so we have it in our tool kit !
First, we need to load in our DDS from 0
# Load DDS to perform Rlog count analysis
```{r load dds for mouse long time course DESEQ2}
# Loading DDS
load("../06_Differential_expression_analyses/results/dds_time_point_mouse_long.RData", verbose = TRUE)
# First Normalize counts (rlog) function in DESEQ2
# This basically is rank counts normalized to std error in replicates.
rlog_counts_mouse_long <- rlog(dds_time_point, blind = TRUE)
library(DESeq2)
# Now we retrieve the values using the "assay" function that converts to rlog_counts)
rlog_counts_matrix_mouse_long <- assay(rlog_counts_mouse_long)
# which(is.na(rlog_counts_mouse_long))
breaks <- seq(-2, 2, length.out = 51)
# Filter to sig genes
sig_rlog_counts_matrix_mouse_long <- rlog_counts_matrix_mouse_long[rownames(rlog_counts_matrix_mouse_long) %in% unique_sig_genes, ]
# Plotting heatmap
pheatmap(sig_rlog_counts_matrix_mouse_long,
cluster_rows = TRUE,
cluster_cols = TRUE,
scale = "row",
show_rownames = FALSE,
show_colnames = TRUE,
main = "Heatmap of Sig genes Rlog-Transformed Values",
breaks = breaks,
color = colorRampPalette(c("blue", "white", "red"))(50) # Gradient from blue to red
)
# now filter to sig genes
sig_rlog_counts_matrix_mouse_long <- rlog_counts_matrix_mouse_long[rownames(rlog_counts_matrix_mouse_long) %in% unique_sig_genes, ]
# Plot heap map of Rlog counts of sig genes
pheatmap(sig_rlog_counts_matrix_mouse_long,
cluster_rows = TRUE,
cluster_cols = TRUE,
scale = "row",
show_rownames = FALSE,
show_colnames = TRUE,
main = "Heatmap of Rlog-Transformed Values" )
# Now let's order again
ordered_matrix <- sig_rlog_counts_matrix_mouse_long[, order(colnames(sig_rlog_counts_matrix_mouse_long))]
# Create the heatmap with columns ordered by name
pheatmap(ordered_matrix,
cluster_rows = TRUE,
cluster_cols = FALSE, # Do not cluster columns, just order by name
scale = "row",
show_rownames = FALSE,
show_colnames = TRUE,
main = "Heatmap of Sig genes Rlog-Transformed Values",
breaks = breaks,
color = colorRampPalette(c("blue", "white", "red"))(50) # Gradient from blue to red
)
# NICE !! We are heatmap pros now !!
# Now we can write this out and START from here in the future.
# create new folder 'rlog_count_matrices'
library(readr)
write_rds(rlog_counts_matrix_mouse_long, "results/rlog_counts_all.rds")
```
################## ExeRcise ##################
Now you should be able to make a heatmap for any gene list.
Make a custom gene list based on properties of genes responding
to dox in whatever way you want. Then make a heatmap. Or maybe
test your skills and make a heatmap of one gene :) Finally,
you could sharpen skills by making the heat map very custom
and maybe even a funciton that creates a heatmap !!!!
##############################################
# BONUS : find average and plot heatmap :)
Let's grab the average values using a short set of code
Then plot heat map with average rlog counts (same for TPM matrix)
```{r get average values and plot heatmap}
# Splitting col names to get sample info for average
split_names <- strsplit(colnames(ordered_matrix), "_")
# Extract the time point part of the names (the first two elements combined)
time_points <- sapply(split_names, function(x) paste(x[1], x[2], sep = "_"))
# Calculate the mean across replicates for each time point
average_matrix <- sapply(unique(time_points), function(tp) {
rowMeans(ordered_matrix[, time_points == tp, drop = FALSE])
})
# Convert the result back to a matrix with appropriate row and column names
average_matrix <- as.matrix(average_matrix)
rownames(average_matrix) <- rownames(ordered_matrix)
colnames(average_matrix) <- unique(time_points)
# Now you can plot the heatmap using the averaged matrix
pheatmap(average_matrix,
cluster_rows = TRUE,
cluster_cols = FALSE, # Do not cluster columns, just order by time point
scale = "row",
show_rownames = FALSE,
show_colnames = TRUE,
main = "Heatmap of Sig genes Rlog-Transformed Values (Averaged by Time Point)",
breaks = breaks,
color = colorRampPalette(c("blue", "white", "red"))(50) # Gradient from blue to red
)
```
# Also color schemes are a thing - here are some others to try:
# Here are some cool colorRampPalette options for heatmaps of RNA sequencing data:
# 1. Viridis
# A popular choice for heatmaps, as it's perceptually uniform and accessible for colorblind individuals.
# colorRampPalette(c("#440154", "#2b8cbe", "#f7f7f7", "#fed976", "#fb8a54"))
# 2. Inferno
# A smooth, continuous palette that works well for displaying gene expression values.
# colorRampPalette(c("#000000", "#2c3e50", "#8e44ad", "#f1c40f", "#e74c3c"))
# 3. Plasma
# A vibrant, blue-dominated palette that's perfect for highlighting differentially expressed genes.
# colorRampPalette(c("#2c7bb6", "#00a6ca", "#f7f7f7", "#edc949", "#e67e73"))
# 4. Magma
# A warm, orange-yellow palette that's great for showing gene expression intensity.
# colorRampPalette(c("#000000", "#4a0a4a", "#f2c464", "#f7dc6f", "#fdbe3b"))
# 5. Blue-Red Diverging
# A classic diverging palette that's useful for displaying log-fold changes or correlation values.
# colorRampPalette(c("#2196f3", "#ffffff", "#f44336"))