1 Purpose of this analysis

In this example, we use weighted gene co-expression network analysis (WGCNA) to identify co-expressed gene modules (Langfelder and Horvath 2008). WGCNA uses a series of correlations to identify sets of genes that are expressed together in your data set. This is a fairly intuitive approach to gene network analysis which can aid in interpretation of microarray & RNA-seq data.

As output, WGCNA gives groups of co-expressed genes as well as an eigengene x sample matrix (where the values for each eigengene represent the summarized expression for a group of co-expressed genes) (Langfelder and Horvath 2007). This eigengene x sample data can, in many instances, be used as you would the original gene expression values. In this example, we use eigengene x sample data to identify differentially expressed modules between our treatment and control group

This method does require some computing power, but can still be run locally (on your own computer) for most refine.bio datasets. As with many clustering and network methods, there are some parameters that may need tweaking.

⬇️ Jump to the analysis code ⬇️

2 How to run this example

For general information about our tutorials and the basic software packages you will need, please see our ‘Getting Started’ section. We recommend taking a look at our Resources for Learning R if you have not written code in R before.

2.1 Obtain the .Rmd file

To run this example yourself, download the .Rmd for this analysis by clicking this link.

Clicking this link will most likely send this to your downloads folder on your computer. Move this .Rmd file to where you would like this example and its files to be stored.

You can open this .Rmd file in RStudio and follow the rest of these steps from there. (See our section about getting started with R notebooks if you are unfamiliar with .Rmd files.)

2.2 Set up your analysis folders

Good file organization is helpful for keeping your data analysis project on track! We have set up some code that will automatically set up a folder structure for you. Run this next chunk to set up your folders!

If you have trouble running this chunk, see our introduction to using .Rmds for more resources and explanations.

# Create the data folder if it doesn't exist
if (!dir.exists("data")) {
  dir.create("data")
}

# Define the file path to the plots directory
plots_dir <- "plots"

# Create the plots folder if it doesn't exist
if (!dir.exists(plots_dir)) {
  dir.create(plots_dir)
}

# Define the file path to the results directory
results_dir <- "results"

# Create the results folder if it doesn't exist
if (!dir.exists(results_dir)) {
  dir.create(results_dir)
}

In the same place you put this .Rmd file, you should now have three new empty folders called data, plots, and results!

2.3 Obtain the dataset from refine.bio

For general information about downloading data for these examples, see our ‘Getting Started’ section.

Go to this dataset’s page on refine.bio.

Click the “Download Now” button on the right side of this screen.

Fill out the pop up window with your email and our Terms and Conditions:

We are going to use non-quantile normalized data for this analysis. To get this data, you will need to check the box that says “Skip quantile normalization for RNA-seq samples.” Note that this option will only be available for RNA-seq datasets.

It may take a few minutes for the dataset to process. You will get an email when it is ready.

2.4 About the dataset we are using for this example

For this example analysis, we will use this acute viral bronchiolitis dataset. The data that we downloaded from refine.bio for this analysis has 62 paired peripheral blood mononuclear cell RNA-seq samples obtained from 31 patients. Samples were collected at two time points: during their first, acute bronchiolitis visit (abbreviated “AV”) and their recovery, their post-convalescence visit (abbreviated “CV”).

2.5 Place the dataset in your new data/ folder

refine.bio will send you a download button in the email when it is ready. Follow the prompt to download a zip file that has a name with a series of letters and numbers and ends in .zip. Double clicking should unzip this for you and create a folder of the same name.

For more details on the contents of this folder see these docs on refine.bio.

The <experiment_accession_id> folder has the data and metadata TSV files you will need for this example analysis. Experiment accession ids usually look something like GSE1235 or SRP12345.

Copy and paste the SRP140558 folder into your newly created data/ folder.

2.6 Check out our file structure!

Your new analysis folder should contain:

  • The example analysis .Rmd you downloaded
  • A folder called “data” which contains:
    • The SRP140558 folder which contains:
      • The gene expression
      • The metadata TSV
  • A folder for plots (currently empty)
  • A folder for results (currently empty)

Your example analysis folder should now look something like this (except with respective experiment accession ID and analysis notebook name you are using):

In order for our example here to run without a hitch, we need these files to be in these locations so we’ve constructed a test to check before we get started with the analysis. These chunks will declare your file paths and double check that your files are in the right place.

First we will declare our file paths to our data and metadata files, which should be in our data directory. This is handy to do because if we want to switch the dataset (see next section for more on this) we are using for this analysis, we will only have to change the file path here to get started.

# Define the file path to the data directory
# Replace with the path of the folder the files will be in
data_dir <- file.path("data", "SRP140558")

# Declare the file path to the gene expression matrix file
# inside directory saved as `data_dir`
# Replace with the path to your dataset file
data_file <- file.path(data_dir, "SRP140558.tsv")

# Declare the file path to the metadata file
# inside the directory saved as `data_dir`
# Replace with the path to your metadata file
metadata_file <- file.path(data_dir, "metadata_SRP140558.tsv")

Now that our file paths are declared, we can use the file.exists() function to check that the files are where we specified above.

# Check if the gene expression matrix file is at the path stored in `data_file`
file.exists(data_file)
## [1] TRUE
# Check if the metadata file is at the file path stored in `metadata_file`
file.exists(metadata_file)
## [1] TRUE

If the chunk above printed out FALSE to either of those tests, you won’t be able to run this analysis as is until those files are in the appropriate place.

If the concept of a “file path” is unfamiliar to you; we recommend taking a look at our section about file paths.

3 Using a different refine.bio dataset with this analysis?

If you’d like to adapt an example analysis to use a different dataset from refine.bio, we recommend placing the files in the data/ directory you created and changing the filenames and paths in the notebook to match these files (we’ve put comments to signify where you would need to change the code). We suggest saving plots and results to plots/ and results/ directories, respectively, as these are automatically created by the notebook. From here you can customize this analysis example to fit your own scientific questions and preferences.

3.0.1 Sample size

Keep in mind when using a different refine.bio dataset with this example, that WGCNA requires at least 15 samples to produce a meaningful result according to its authors. So you will need to make sure the dataset you use is sufficiently large. However, note that very large datasets will be difficult to run locally (on a personal laptop) due to the required computing power. While you can adjust some parameters to make this more doable on a laptop, it may decrease the reliability of your result if taken to an extreme (more on this parameter, called maxBlockSize, in the Run WGCNA! section).

3.0.2 Microarray vs RNA-seq

WGCNA can be used with both RNA-seq and microarray datasets so long as they are well normalized and filtered. In this example we use RNA-seq and normalize and transform the data with DESeq2’s vst(), which not only is a method and package we recommend in general, but is also the authors’ specific recommendations for using WGCNA with RNA-seq data.

If you end up wanting to run WGCNA with a microarray dataset, the normalization done by refine.bio should be sufficient, but you will likely want to apply a minimum expression filter as we do in this example. If you have troubles finding a power parameter that yields a sufficient R^2 even after applying a stringent cutoff, you may want to look into using a different dataset.


 

4 Identifying co-expression gene modules with WGCNA - RNA-seq

4.1 Install libraries

See our Getting Started page with instructions for package installation for a list of the other software you will need, as well as more tips and resources.

We will be using DESeq2 to normalize and transform our RNA-seq data before running WGCNA, so we will need to install that (Love et al. 2014).

Of course, we will need the WGCNA package (Langfelder and Horvath 2008). But WGCNA also requires a package called impute that it sometimes has trouble installing so we recommend installing that first (Hastie et al. 2020).

For plotting purposes will be creating a sina plot and heatmaps which we will need a ggplot2 companion package for, called ggforce as well as the ComplexHeatmap package (Gu 2020).

if (!("DESeq2" %in% installed.packages())) {
  # Install this package if it isn't installed yet
  BiocManager::install("DESeq2", update = FALSE)
}

if (!("impute" %in% installed.packages())) {
  # Install this package if it isn't installed yet
  BiocManager::install("impute")
}

if (!("WGCNA" %in% installed.packages())) {
  # Install this package if it isn't installed yet
  install.packages("WGCNA")
}

if (!("ggforce" %in% installed.packages())) {
  # Install this package if it isn't installed yet
  install.packages("ggforce")
}

if (!("ComplexHeatmap" %in% installed.packages())) {
  # Install this package if it isn't installed yet
  install.packages("ComplexHeatmap")
}

Attach some of the packages we need for this analysis.

# Attach the DESeq2 library
library(DESeq2)

# We will need this so we can use the pipe: %>%
library(magrittr)

# We'll need this for finding gene modules
library(WGCNA)

# We'll be making some plots
library(ggplot2)

4.2 Import and set up data

Data downloaded from refine.bio include a metadata tab separated values (TSV) file and a data TSV file. This chunk of code will read the both TSV files and add them as data frames to your environment.

We stored our file paths as objects named metadata_file and data_file in this previous step.

# Read in metadata TSV file
metadata <- readr::read_tsv(metadata_file)
## 
## ── Column specification ──────────────────────────────────────────────
## cols(
##   .default = col_logical(),
##   refinebio_accession_code = col_character(),
##   experiment_accession = col_character(),
##   refinebio_organism = col_character(),
##   refinebio_platform = col_character(),
##   refinebio_source_database = col_character(),
##   refinebio_subject = col_character(),
##   refinebio_title = col_character()
## )
## ℹ Use `spec()` for the full column specifications.
# Read in data TSV file
df <- readr::read_tsv(data_file) %>%
  # Here we are going to store the gene IDs as row names so that we can have a numeric matrix to perform calculations on later
  tibble::column_to_rownames("Gene")
## 
## ── Column specification ──────────────────────────────────────────────
## cols(
##   .default = col_double(),
##   Gene = col_character()
## )
## ℹ Use `spec()` for the full column specifications.

Let’s ensure that the metadata and data are in the same sample order.

# Make the data in the order of the metadata
df <- df %>%
  dplyr::select(metadata$refinebio_accession_code)

# Check if this is in the same order
all.equal(colnames(df), metadata$refinebio_accession_code)
## [1] TRUE

4.2.1 Prepare data for DESeq2

There are two things we need to do to prep our expression data for DESeq2.

First, we need to make sure all of the values in our data are converted to integers as required by a DESeq2 function we will use later.

Then, we need to filter out the genes that have not been expressed or that have low expression counts. This is recommended by WGCNA docs for RNA-seq data. Removing low count genes can also help improve your WGCNA results. We are going to do some pre-filtering to keep only genes with 50 or more reads in total across the samples.

# The next DESeq2 functions need the values to be converted to integers
df <- round(df) %>%
  # The next steps require a data frame and round() returns a matrix
  as.data.frame() %>%
  # Only keep rows that have total counts above the cutoff
  dplyr::filter(rowSums(.) >= 50)

Another thing we need to do is set up our main experimental group variable. Unfortunately the metadata for this dataset are not set up into separate, neat columns, but we can accomplish that ourselves.

For this study, PBMCs were collected at two time points: during the patients’ first, acute bronchiolitis visit (abbreviated “AV”) and their recovery visit, (called post-convalescence and abbreviated “CV”).

For handier use of this information, we can create a new variable, time_point, that states this info more clearly. This new time_point variable will have two labels: acute illness and recovering based on the AV or CV coding located in the refinebio_title string variable.

metadata <- metadata %>%
  dplyr::mutate(
    time_point = dplyr::case_when(
      # Create our new variable based on refinebio_title containing AV/CV
      stringr::str_detect(refinebio_title, "_AV_") ~ "acute illness",
      stringr::str_detect(refinebio_title, "_CV_") ~ "recovering"
    ),
    # It's easier for future items if this is already set up as a factor
    time_point = as.factor(time_point)
  )

Let’s double check that our factor set up is right. We want acute illness to be the first level since it was the first time point collected.

levels(metadata$time_point)
## [1] "acute illness" "recovering"

Great! We’re all set.

4.3 Create a DESeqDataset

We will be using the DESeq2 package for normalizing and transforming our data, which requires us to format our data into a DESeqDataSet object. We turn the data frame (or matrix) into a DESeqDataSet object and specify which variable labels our experimental groups using the design argument (Love et al. 2014). In this chunk of code, we will not provide a specific model to the design argument because we are not performing a differential expression analysis.

# Create a `DESeqDataSet` object
dds <- DESeqDataSetFromMatrix(
  countData = df, # Our prepped data frame with counts
  colData = metadata, # Data frame with annotation for our samples
  design = ~1 # Here we are not specifying a model
)
## converting counts to integer mode

4.4 Perform DESeq2 normalization and transformation

We often suggest normalizing and transforming your data for various applications and in this instance WGCNA’s authors suggest using variance stabilizing transformation before running WGCNA.
We are going to use the vst() function from the DESeq2 package to normalize and transform the data. For more information about these transformation methods, see here.

# Normalize and transform the data in the `DESeqDataSet` object using the `vst()`
# function from the `DESEq2` R package
dds_norm <- vst(dds)

At this point, if your data set has any outlier samples, you should look into removing them as they can affect your WGCNA results.

WGCNA’s tutorial has an example of exploring your data for outliers you can reference.

For this example data set, we will skip this step (there are no obvious outliers) and proceed.

4.5 Format normalized data for WGCNA

Extract the normalized counts to a matrix and transpose it so we can pass it to WGCNA.

# Retrieve the normalized data from the `DESeqDataSet`
normalized_counts <- assay(dds_norm) %>%
  t() # Transpose this data

4.6 Determine parameters for WGCNA

To identify which genes are in the same modules, WGCNA first creates a weighted network to define which genes are near each other. The measure of “adjacency” it uses is based on the correlation matrix, but requires the definition of a threshold value, which in turn depends on a “power” parameter that defines the exponent used when transforming the correlation values. The choice of power parameter will affect the number of modules identified, and the WGCNA modules provides the pickSoftThreshold() function to help identify good choices for this parameter.

sft <- pickSoftThreshold(normalized_counts,
  dataIsExpr = TRUE,
  corFnc = cor,
  networkType = "signed"
)
## Warning: executing %dopar% sequentially: no parallel backend
## registered
##    Power SFT.R.sq  slope truncated.R.sq mean.k. median.k. max.k.
## 1      1   0.0491  42.50          0.947 13400.0  13400.00  13600
## 2      2   0.8530 -12.60          0.871  7230.0   7080.00   8430
## 3      3   0.8800  -5.41          0.856  4120.0   3900.00   5840
## 4      4   0.8910  -3.28          0.864  2470.0   2230.00   4340
## 5      5   0.9060  -2.39          0.882  1560.0   1310.00   3380
## 6      6   0.9140  -1.96          0.895  1030.0    798.00   2740
## 7      7   0.9220  -1.72          0.908   706.0    496.00   2280
## 8      8   0.9190  -1.58          0.910   504.0    314.00   1940
## 9      9   0.9180  -1.48          0.917   371.0    203.00   1680
## 10    10   0.9080  -1.42          0.915   282.0    134.00   1470
## 11    12   0.9050  -1.34          0.927   174.0     60.40   1170
## 12    14   0.8870  -1.31          0.927   116.0     28.60    964
## 13    16   0.8660  -1.32          0.918    81.7     14.00    810
## 14    18   0.8560  -1.33          0.921    59.7      7.13    692
## 15    20   0.8570  -1.33          0.929    45.0      3.71    599

This sft object has a lot of information, we will want to plot some of it to figure out what our power soft-threshold should be. We have to first calculate a measure of the model fit, the signed \(R^2\), and make that a new variable.

sft_df <- data.frame(sft$fitIndices) %>%
  dplyr::mutate(model_fit = -sign(slope) * SFT.R.sq)

Now, let’s plot the model fitting by the power soft threshold so we can decide on a soft-threshold for power.

ggplot(sft_df, aes(x = Power, y = model_fit, label = Power)) +
  # Plot the points
  geom_point() +
  # We'll put the Power labels slightly above the data points
  geom_text(nudge_y = 0.1) +
  # We will plot what WGCNA recommends as an R^2 cutoff
  geom_hline(yintercept = 0.80, col = "red") +
  # Just in case our values are low, we want to make sure we can still see the 0.80 level
  ylim(c(min(sft_df$model_fit), 1.05)) +
  # We can add more sensible labels for our axis
  xlab("Soft Threshold (power)") +
  ylab("Scale Free Topology Model Fit, signed R^2") +
  ggtitle("Scale independence") +
  # This adds some nicer aesthetics to our plot
  theme_classic()

Using this plot we can decide on a power parameter. WGCNA’s authors recommend using a power that has an signed \(R^2\) above 0.80, otherwise they warn your results may be too noisy to be meaningful.

If you have multiple power values with signed \(R^2\) above 0.80, then picking the one at an inflection point, in other words where the \(R^2\) values seem to have reached their saturation (Zhang and Horvath 2005). You want to a power that gives you a big enough \(R^2\) but is not excessively large.

So using the plot above, going with a power soft-threshold of 7!

If you find you have all very low \(R^2\) values this may be because there are too many genes with low expression values that are cluttering up the calculations. You can try returning to gene filtering step and choosing a more stringent cutoff (you’ll then need to re-run the transformation and subsequent steps to remake this plot to see if that helped).

4.7 Run WGCNA!

We will use the blockwiseModules() function to find gene co-expression modules in WGCNA, using 7 for the power argument like we determined above.

This next step takes some time to run. The blockwise part of the blockwiseModules() function name refers to that these calculations will be done on chunks of your data at a time to help with conserving computing resources.

Here we are using the default maxBlockSize, 5000 but, you may want to adjust the maxBlockSize argument depending on your computer’s memory. The authors of WGCNA recommend running the largest block your computer can handle and they provide some approximations as to GB of memory of a laptop and what maxBlockSize it should be able to handle:

• If the reader has access to a large workstation with more than 4 GB of memory, the parameter maxBlockSize can be increased. A 16GB workstation should handle up to 20000 probes; a 32GB workstation should handle perhaps 30000. A 4GB standard desktop or a laptop may handle up to 8000-10000 probes, depending on operating system and other running programs.

(Langfelder and Horvath 2016)

bwnet <- blockwiseModules(normalized_counts,
  maxBlockSize = 5000, # What size chunks (how many genes) the calculations should be run in
  TOMType = "signed", # topological overlap matrix
  power = 7, # soft threshold for network construction
  numericLabels = TRUE, # Let's use numbers instead of colors for module labels
  randomSeed = 1234, # there's some randomness associated with this calculation
  # so we should set a seed
)

The TOMtype argument specifies what kind of topological overlap matrix (TOM) should be used to make gene modules. You can safely assume for most situations a signed network represents what you want – we want WGCNA to pay attention to directionality. However if you suspect you may benefit from an unsigned network, where positive/negative is ignored see this article to help you figure that out (Langfelder 2018).

There are a lot of other settings you can tweak – look at ?blockwiseModules help page as well as the WGCNA tutorial (Langfelder and Horvath 2016).

4.8 Write main WGCNA results object to file

We will save our whole results object to an RDS file in case we want to return to our original WGCNA results.

readr::write_rds(bwnet,
  file = file.path("results", "SRP140558_wgcna_results.RDS")
)

4.9 Explore our WGCNA results

The bwnet object has many parts, storing a lot of information. We can pull out the parts we are most interested in and may want to use use for plotting.

In bwnet we have a data frame of eigengene module data for each sample in the MEs slot. These represent the collapsed, combined, and normalized expression of the genes that make up each module.

module_eigengenes <- bwnet$MEs

# Print out a preview
head(module_eigengenes)

4.10 Which modules have biggest differences across treatment groups?

We can also see if our eigengenes relate to our metadata labels. First we double check that our samples are still in order.

all.equal(metadata$refinebio_accession_code, rownames(module_eigengenes))
## [1] TRUE
# Create the design matrix from the `time_point` variable
des_mat <- model.matrix(~ metadata$time_point)

Run linear model on each module. Limma wants our tests to be per row, so we also need to transpose so the eigengenes are rows

# lmFit() needs a transposed version of the matrix
fit <- limma::lmFit(t(module_eigengenes), design = des_mat)

# Apply empirical Bayes to smooth standard errors
fit <- limma::eBayes(fit)

Apply multiple testing correction and obtain stats in a data frame.

# Apply multiple testing correction and obtain stats
stats_df <- limma::topTable(fit, number = ncol(module_eigengenes)) %>%
  tibble::rownames_to_column("module")
## Removing intercept from test coefficients

Let’s take a look at the results. They are sorted with the most significant results at the top.

head(stats_df)

Module 19 seems to be the most differentially expressed across time_point groups. Now we can do some investigation into this module.

4.11 Let’s make plot of module 19

As a sanity check, let’s use ggplot to see what module 18’s eigengene looks like between treatment groups.

First we need to set up the module eigengene for this module with the sample metadata labels we need.

module_19_df <- module_eigengenes %>%
  tibble::rownames_to_column("accession_code") %>%
  # Here we are performing an inner join with a subset of metadata
  dplyr::inner_join(metadata %>%
    dplyr::select(refinebio_accession_code, time_point),
  by = c("accession_code" = "refinebio_accession_code")
  )

Now we are ready for plotting.

ggplot(
  module_19_df,
  aes(
    x = time_point,
    y = ME19,
    color = time_point
  )
) +
  # a boxplot with outlier points hidden (they will be in the sina plot)
  geom_boxplot(width = 0.2, outlier.shape = NA) +
  # A sina plot to show all of the individual data points
  ggforce::geom_sina(maxwidth = 0.3) +
  theme_classic()

This makes sense! Looks like module 19 has elevated expression during the acute illness but not when recovering.

4.12 What genes are a part of module 19?

If you want to know which of your genes make up a modules, you can look at the $colors slot. This is a named list which associates the genes with the module they are a part of. We can turn this into a data frame for handy use.

gene_module_key <- tibble::enframe(bwnet$colors, name = "gene", value = "module") %>%
  # Let's add the `ME` part so its more clear what these numbers are and it matches elsewhere
  dplyr::mutate(module = paste0("ME", module))

Now we can find what genes are a part of module 19.

gene_module_key %>%
  dplyr::filter(module == "ME19")

Let’s save this gene to module key to a TSV file for future use.

readr::write_tsv(gene_module_key,
  file = file.path("results", "SRP140558_wgcna_gene_to_module.tsv")
)

4.13 Make a custom heatmap function

We will make a heatmap that summarizes our differentially expressed module. Because we will make a couple of these, it makes sense to make a custom function for making this heatmap.

make_module_heatmap <- function(module_name,
                                expression_mat = normalized_counts,
                                metadata_df = metadata,
                                gene_module_key_df = gene_module_key,
                                module_eigengenes_df = module_eigengenes) {
  # Create a summary heatmap of a given module.
  #
  # Args:
  # module_name: a character indicating what module should be plotted, e.g. "ME19"
  # expression_mat: The full gene expression matrix. Default is `normalized_counts`.
  # metadata_df: a data frame with refinebio_accession_code and time_point
  #              as columns. Default is `metadata`.
  # gene_module_key: a data.frame indicating what genes are a part of what modules. Default is `gene_module_key`.
  # module_eigengenes: a sample x eigengene data.frame with samples as row names. Default is `module_eigengenes`.
  #
  # Returns:
  # A heatmap of expression matrix for a module's genes, with a barplot of the
  # eigengene expression for that module.

  # Set up the module eigengene with its refinebio_accession_code
  module_eigengene <- module_eigengenes_df %>%
    dplyr::select(all_of(module_name)) %>%
    tibble::rownames_to_column("refinebio_accession_code")

  # Set up column annotation from metadata
  col_annot_df <- metadata_df %>%
    # Only select the treatment and sample ID columns
    dplyr::select(refinebio_accession_code, time_point, refinebio_subject) %>%
    # Add on the eigengene expression by joining with sample IDs
    dplyr::inner_join(module_eigengene, by = "refinebio_accession_code") %>%
    # Arrange by patient and time point
    dplyr::arrange(time_point, refinebio_subject) %>%
    # Store sample
    tibble::column_to_rownames("refinebio_accession_code")

  # Create the ComplexHeatmap column annotation object
  col_annot <- ComplexHeatmap::HeatmapAnnotation(
    # Supply treatment labels
    time_point = col_annot_df$time_point,
    # Add annotation barplot
    module_eigengene = ComplexHeatmap::anno_barplot(dplyr::select(col_annot_df, module_name)),
    # Pick colors for each experimental group in time_point
    col = list(time_point = c("recovering" = "#f1a340", "acute illness" = "#998ec3"))
  )

  # Get a vector of the Ensembl gene IDs that correspond to this module
  module_genes <- gene_module_key_df %>%
    dplyr::filter(module == module_name) %>%
    dplyr::pull(gene)

  # Set up the gene expression data frame
  mod_mat <- expression_mat %>%
    t() %>%
    as.data.frame() %>%
    # Only keep genes from this module
    dplyr::filter(rownames(.) %in% module_genes) %>%
    # Order the samples to match col_annot_df
    dplyr::select(rownames(col_annot_df)) %>%
    # Data needs to be a matrix
    as.matrix()

  # Normalize the gene expression values
  mod_mat <- mod_mat %>%
    # Scale can work on matrices, but it does it by column so we will need to
    # transpose first
    t() %>%
    scale() %>%
    # And now we need to transpose back
    t()

  # Create a color function based on standardized scale
  color_func <- circlize::colorRamp2(
    c(-2, 0, 2),
    c("#67a9cf", "#f7f7f7", "#ef8a62")
  )

  # Plot on a heatmap
  heatmap <- ComplexHeatmap::Heatmap(mod_mat,
    name = module_name,
    # Supply color function
    col = color_func,
    # Supply column annotation
    bottom_annotation = col_annot,
    # We don't want to cluster samples
    cluster_columns = FALSE,
    # We don't need to show sample or gene labels
    show_row_names = FALSE,
    show_column_names = FALSE
  )

  # Return heatmap
  return(heatmap)
}

4.14 Make module heatmaps

Let’s try out the custom heatmap function with module 19 (our most differentially expressed module).

mod_19_heatmap <- make_module_heatmap(module_name = "ME19")
## Note: Using an external vector in selections is ambiguous.
## ℹ Use `all_of(module_name)` instead of `module_name` to silence this message.
## ℹ See <https://tidyselect.r-lib.org/reference/faq-external-vector.html>.
## This message is displayed once per session.
# Print out the plot
mod_19_heatmap

From the barplot portion of our plot, we can see acute illness samples tend to have higher expression values for the module 19 eigengene. In the heatmap portion, we can see how the individual genes that make up module 19 are overall higher than in the recovering samples.

We can save this plot to PNG.

png(file.path("results", "SRP140558_module_19_heatmap.png"))
mod_19_heatmap
dev.off()
## png 
##   2

For comparison, let’s try out the custom heatmap function with a different, not differentially expressed module.

mod_25_heatmap <- make_module_heatmap(module_name = "ME25")

# Print out the plot
mod_25_heatmap

In this non-significant module’s heatmap, there’s not a particularly strong pattern between acute illness and recovery samples. Though we can still see the genes in this module seem to be very correlated with each other (which is how we found them in the first place, so this makes sense!).

Save this plot also.

png(file.path("results", "SRP140558_module_25_heatmap.png"))
mod_25_heatmap
dev.off()
## png 
##   2

6 Session info

At the end of every analysis, before saving your notebook, we recommend printing out your session info. This helps make your code more reproducible by recording what versions of software and packages you used to run this.

# Print session info
sessioninfo::session_info()
## ─ Session info ─────────────────────────────────────────────────────
##  setting  value                       
##  version  R version 4.0.5 (2021-03-31)
##  os       Ubuntu 20.04.3 LTS          
##  system   x86_64, linux-gnu           
##  ui       X11                         
##  language (EN)                        
##  collate  en_US.UTF-8                 
##  ctype    en_US.UTF-8                 
##  tz       Etc/UTC                     
##  date     2022-03-01                  
## 
## ─ Packages ─────────────────────────────────────────────────────────
##  package              * version  date       lib source        
##  annotate               1.68.0   2020-10-27 [1] Bioconductor  
##  AnnotationDbi          1.52.0   2020-10-27 [1] Bioconductor  
##  assertthat             0.2.1    2019-03-21 [1] RSPM (R 4.0.3)
##  backports              1.2.1    2020-12-09 [1] RSPM (R 4.0.3)
##  base64enc              0.1-3    2015-07-28 [1] RSPM (R 4.0.3)
##  Biobase              * 2.50.0   2020-10-27 [1] Bioconductor  
##  BiocGenerics         * 0.36.1   2021-04-16 [1] Bioconductor  
##  BiocParallel           1.24.1   2020-11-06 [1] Bioconductor  
##  bit                    4.0.4    2020-08-04 [1] RSPM (R 4.0.3)
##  bit64                  4.0.5    2020-08-30 [1] RSPM (R 4.0.3)
##  bitops                 1.0-7    2021-04-24 [1] RSPM (R 4.0.4)
##  blob                   1.2.1    2020-01-20 [1] RSPM (R 4.0.3)
##  bslib                  0.2.5    2021-05-12 [1] RSPM (R 4.0.4)
##  cachem                 1.0.5    2021-05-15 [1] RSPM (R 4.0.4)
##  Cairo                  1.5-12.2 2020-07-07 [1] RSPM (R 4.0.5)
##  checkmate              2.0.0    2020-02-06 [1] RSPM (R 4.0.3)
##  circlize               0.4.12   2021-01-08 [1] RSPM (R 4.0.3)
##  cli                    2.5.0    2021-04-26 [1] RSPM (R 4.0.4)
##  clue                   0.3-59   2021-04-16 [1] RSPM (R 4.0.4)
##  cluster                2.1.2    2021-04-17 [1] RSPM (R 4.0.4)
##  codetools              0.2-18   2020-11-04 [2] CRAN (R 4.0.5)
##  colorspace             2.0-1    2021-05-04 [1] RSPM (R 4.0.4)
##  ComplexHeatmap         2.6.2    2020-11-12 [1] Bioconductor  
##  crayon                 1.4.1    2021-02-08 [1] RSPM (R 4.0.3)
##  data.table             1.14.0   2021-02-21 [1] RSPM (R 4.0.3)
##  DBI                    1.1.1    2021-01-15 [1] RSPM (R 4.0.3)
##  DelayedArray           0.16.3   2021-03-24 [1] Bioconductor  
##  DESeq2               * 1.30.1   2021-02-19 [1] Bioconductor  
##  digest                 0.6.27   2020-10-24 [1] RSPM (R 4.0.3)
##  doParallel             1.0.16   2020-10-16 [1] RSPM (R 4.0.3)
##  dplyr                  1.0.6    2021-05-05 [1] RSPM (R 4.0.4)
##  dynamicTreeCut       * 1.63-1   2016-03-11 [1] RSPM (R 4.0.0)
##  ellipsis               0.3.2    2021-04-29 [1] RSPM (R 4.0.4)
##  evaluate               0.14     2019-05-28 [1] RSPM (R 4.0.3)
##  fansi                  0.4.2    2021-01-15 [1] RSPM (R 4.0.3)
##  farver                 2.1.0    2021-02-28 [1] RSPM (R 4.0.3)
##  fastcluster          * 1.1.25   2018-06-07 [1] RSPM (R 4.0.3)
##  fastmap                1.1.0    2021-01-25 [1] RSPM (R 4.0.3)
##  foreach                1.5.1    2020-10-15 [1] RSPM (R 4.0.3)
##  foreign                0.8-81   2020-12-22 [2] CRAN (R 4.0.5)
##  Formula                1.2-4    2020-10-16 [1] RSPM (R 4.0.3)
##  genefilter             1.72.1   2021-01-21 [1] Bioconductor  
##  geneplotter            1.68.0   2020-10-27 [1] Bioconductor  
##  generics               0.1.0    2020-10-31 [1] RSPM (R 4.0.3)
##  GenomeInfoDb         * 1.26.7   2021-04-08 [1] Bioconductor  
##  GenomeInfoDbData       1.2.4    2022-03-01 [1] Bioconductor  
##  GenomicRanges        * 1.42.0   2020-10-27 [1] Bioconductor  
##  getopt                 1.20.3   2019-03-22 [1] RSPM (R 4.0.0)
##  GetoptLong             1.0.5    2020-12-15 [1] RSPM (R 4.0.3)
##  ggforce                0.3.3    2021-03-05 [1] RSPM (R 4.0.3)
##  ggplot2              * 3.3.3    2020-12-30 [1] RSPM (R 4.0.3)
##  GlobalOptions          0.1.2    2020-06-10 [1] RSPM (R 4.0.3)
##  glue                   1.4.2    2020-08-27 [1] RSPM (R 4.0.3)
##  GO.db                  3.12.1   2022-03-01 [1] Bioconductor  
##  gridExtra              2.3      2017-09-09 [1] RSPM (R 4.0.3)
##  gtable                 0.3.0    2019-03-25 [1] RSPM (R 4.0.3)
##  highr                  0.9      2021-04-16 [1] RSPM (R 4.0.4)
##  Hmisc                  4.5-0    2021-02-28 [1] RSPM (R 4.0.3)
##  hms                    1.0.0    2021-01-13 [1] RSPM (R 4.0.3)
##  htmlTable              2.1.0    2020-09-16 [1] RSPM (R 4.0.3)
##  htmltools              0.5.1.1  2021-01-22 [1] RSPM (R 4.0.3)
##  htmlwidgets            1.5.3    2020-12-10 [1] RSPM (R 4.0.3)
##  httr                   1.4.2    2020-07-20 [1] RSPM (R 4.0.3)
##  impute                 1.64.0   2020-10-27 [1] Bioconductor  
##  IRanges              * 2.24.1   2020-12-12 [1] Bioconductor  
##  iterators              1.0.13   2020-10-15 [1] RSPM (R 4.0.3)
##  jpeg                   0.1-8.1  2019-10-24 [1] RSPM (R 4.0.3)
##  jquerylib              0.1.4    2021-04-26 [1] RSPM (R 4.0.4)
##  jsonlite               1.7.2    2020-12-09 [1] RSPM (R 4.0.3)
##  knitr                  1.33     2021-04-24 [1] RSPM (R 4.0.4)
##  labeling               0.4.2    2020-10-20 [1] RSPM (R 4.0.3)
##  lattice                0.20-41  2020-04-02 [2] CRAN (R 4.0.5)
##  latticeExtra           0.6-29   2019-12-19 [1] RSPM (R 4.0.3)
##  lifecycle              1.0.0    2021-02-15 [1] RSPM (R 4.0.3)
##  limma                  3.46.0   2020-10-27 [1] Bioconductor  
##  locfit                 1.5-9.4  2020-03-25 [1] RSPM (R 4.0.3)
##  magick                 2.7.2    2021-05-02 [1] RSPM (R 4.0.4)
##  magrittr             * 2.0.1    2020-11-17 [1] RSPM (R 4.0.3)
##  MASS                   7.3-53.1 2021-02-12 [2] CRAN (R 4.0.5)
##  Matrix                 1.3-2    2021-01-06 [2] CRAN (R 4.0.5)
##  MatrixGenerics       * 1.2.1    2021-01-30 [1] Bioconductor  
##  matrixStats          * 0.58.0   2021-01-29 [1] RSPM (R 4.0.3)
##  memoise                2.0.0    2021-01-26 [1] RSPM (R 4.0.3)
##  munsell                0.5.0    2018-06-12 [1] RSPM (R 4.0.3)
##  nnet                   7.3-15   2021-01-24 [2] CRAN (R 4.0.5)
##  optparse             * 1.6.6    2020-04-16 [1] RSPM (R 4.0.0)
##  pillar                 1.6.1    2021-05-16 [1] RSPM (R 4.0.4)
##  pkgconfig              2.0.3    2019-09-22 [1] RSPM (R 4.0.3)
##  png                    0.1-7    2013-12-03 [1] RSPM (R 4.0.3)
##  polyclip               1.10-0   2019-03-14 [1] RSPM (R 4.0.3)
##  preprocessCore         1.52.1   2021-01-08 [1] Bioconductor  
##  ps                     1.6.0    2021-02-28 [1] RSPM (R 4.0.3)
##  purrr                  0.3.4    2020-04-17 [1] RSPM (R 4.0.3)
##  R.cache                0.15.0   2021-04-30 [1] RSPM (R 4.0.4)
##  R.methodsS3            1.8.1    2020-08-26 [1] RSPM (R 4.0.3)
##  R.oo                   1.24.0   2020-08-26 [1] RSPM (R 4.0.3)
##  R.utils                2.10.1   2020-08-26 [1] RSPM (R 4.0.3)
##  R6                     2.5.0    2020-10-28 [1] RSPM (R 4.0.3)
##  RColorBrewer           1.1-2    2014-12-07 [1] RSPM (R 4.0.3)
##  Rcpp                   1.0.6    2021-01-15 [1] RSPM (R 4.0.3)
##  RCurl                  1.98-1.3 2021-03-16 [1] RSPM (R 4.0.4)
##  readr                  1.4.0    2020-10-05 [1] RSPM (R 4.0.4)
##  rematch2               2.1.2    2020-05-01 [1] RSPM (R 4.0.3)
##  rjson                  0.2.20   2018-06-08 [1] RSPM (R 4.0.3)
##  rlang                  0.4.11   2021-04-30 [1] RSPM (R 4.0.4)
##  rmarkdown              2.8      2021-05-07 [1] RSPM (R 4.0.4)
##  rpart                  4.1-15   2019-04-12 [2] CRAN (R 4.0.5)
##  RSQLite                2.2.7    2021-04-22 [1] RSPM (R 4.0.4)
##  rstudioapi             0.13     2020-11-12 [1] RSPM (R 4.0.3)
##  S4Vectors            * 0.28.1   2020-12-09 [1] Bioconductor  
##  sass                   0.4.0    2021-05-12 [1] RSPM (R 4.0.4)
##  scales                 1.1.1    2020-05-11 [1] RSPM (R 4.0.3)
##  sessioninfo            1.1.1    2018-11-05 [1] RSPM (R 4.0.3)
##  shape                  1.4.5    2020-09-13 [1] RSPM (R 4.0.3)
##  stringi                1.6.1    2021-05-10 [1] RSPM (R 4.0.4)
##  stringr                1.4.0    2019-02-10 [1] RSPM (R 4.0.3)
##  styler                 1.4.1    2021-03-30 [1] RSPM (R 4.0.4)
##  SummarizedExperiment * 1.20.0   2020-10-27 [1] Bioconductor  
##  survival               3.2-10   2021-03-16 [2] CRAN (R 4.0.5)
##  tibble                 3.1.2    2021-05-16 [1] RSPM (R 4.0.4)
##  tidyselect             1.1.1    2021-04-30 [1] RSPM (R 4.0.4)
##  tweenr                 1.0.2    2021-03-23 [1] RSPM (R 4.0.4)
##  utf8                   1.2.1    2021-03-12 [1] RSPM (R 4.0.3)
##  vctrs                  0.3.8    2021-04-29 [1] RSPM (R 4.0.4)
##  WGCNA                * 1.70-3   2021-02-28 [1] RSPM (R 4.0.5)
##  withr                  2.4.2    2021-04-18 [1] RSPM (R 4.0.4)
##  xfun                   0.23     2021-05-15 [1] RSPM (R 4.0.4)
##  XML                    3.99-0.6 2021-03-16 [1] RSPM (R 4.0.4)
##  xtable                 1.8-4    2019-04-21 [1] RSPM (R 4.0.3)
##  XVector                0.30.0   2020-10-27 [1] Bioconductor  
##  yaml                   2.2.1    2020-02-01 [1] RSPM (R 4.0.3)
##  zlibbioc               1.36.0   2020-10-27 [1] Bioconductor  
## 
## [1] /usr/local/lib/R/site-library
## [2] /usr/local/lib/R/library

References

Gu Z., 2020 ComplexHeatmap complete reference. https://jokergoo.github.io/ComplexHeatmap-reference/book/
Hastie T., R. Tibshirani, B. Narasimhan, and G. Chu, 2020 Impute: Imputation for microarray data. https://www.bioconductor.org/packages/devel/bioc/manuals/impute/man/impute.pdf
Langfelder P., and S. Horvath, 2007 Eigengene networks for studying the relationships between co-expression modules. BMC Systems Biology 1. https://doi.org/10.1186/1752-0509-1-54
Langfelder P., and S. Horvath, 2008 WGCNA: An r package for weighted correlation network analysis. BMC Bioinformatics 9. https://doi.org/10.1186/1471-2105-9-559
Langfelder P., and S. Horvath, 2016 Tutorials for the WGCNA package. https://horvath.genetics.ucla.edu/html/CoexpressionNetwork/Rpackages/WGCNA/Tutorials/
Langfelder P., 2018 Signed or unsigned: Which network type is preferable? https://peterlangfelder.com/2018/11/25/signed-or-unsigned-which-network-type-is-preferable/
Love M. I., W. Huber, and S. Anders, 2014 Moderated estimation of fold change and dispersion for RNA-Seq data with DESeq2. Genome Biology 15. https://doi.org/10.1186/s13059-014-0550-8
Zhang B., and S. Horvath, 2005 A general framework for weighted gene co-expression network analysis. Statistical Applications in Genetics and Molecular Biology 4. https://doi.org/10.2202/1544-6115.1128