Creating Heatmaps in R

In the field of data visualization, a heatmap is a powerful tool that converts numerical matrices into color matrices. It intuitively displays the magnitude, sign, and strength of correlations in data through variations in color intensity or temperature. In R language, heatmaps are commonly used to display correlation matrices, clustering results, or low-dimensional projections of high-dimensional data. Its core logic lies in "mapping": assigning a specific color to each cell value within a two-dimensional dataset, allowing observers to instantly grasp the patterns of data distribution.

R has become an excellent tool for creating heatmaps primarily due to its rich ecosystem of base packages (such as dplyr, ggplot2) and specialized data visualization packages (such as ggridges, pheatmap). Unlike traditional plotting functions, modern heatmap construction in R often relies on raster systems or vector graphics libraries. This enables us to easily customize color mappings, adjust legend styles, and add grid lines, thereby adapting to various complex data analysis scenarios.
For users who want a quick start with concise code, the ggridges package is an excellent choice. Built on the ggplot2 system, it features intuitive syntax that is easy to understand. To create a basic heatmap, we first need to prepare a numerical matrix as our data source. Assume we have a matrix named data_matrix, where rows and columns represent different variables, and the values within cells represent their correlation coefficients.

Executing the following code in R will generate a basic heatmap with a color gradient:

library(ggridges)

# Create a basic heatmap
p <- geom_histogram(
  data = data_matrix,
  aes(x = rownames(data_matrix), y = colnames(data_matrix), fill = data_matrix, alpha = 0.75),
  bins = "fixed",
  binwidth = 1,
  width = 2
)

# Add color mapping and legend
p + scale_fill_gradient(low = "blue", high = "red") + 
  labs(fill = "Correlation")

The key to this code lies in the geom_histogram function, which is used to treat each row or column of the matrix as a categorical variable for plotting. The fill parameter directly references the original numerical data. By setting the low and high parameters, we define the range of color gradients; typically, blue represents negative correlation (lower values), while red represents positive correlation (higher values). This approach not only results in concise code but also produces clear and aesthetically pleasing charts that are well-suited for preliminary presentations in data analysis reports.

Achieving Professional Visualization with the pheatmap Package

When dealing with larger datasets or requiring finer control, the pheatmap package is the preferred choice within the R community. Unlike ggridges, pheatmap is designed specifically for heatmaps and offers advanced features such as clustering analysis, row/column reordering, and custom color mappings. It can automatically perform hierarchical clustering on data based on its overall structure and rearrange rows and columns to highlight similar patterns visually.

The steps to create a heatmap using pheatmap are relatively simple yet highly flexible. Here is a complete example including clustering functionality:

library(pheatmap)

# Define custom color mapping
color_map <- colorRampPalette(c("blue", "white", "red"))(256)

# Create the heatmap
pheatmap(data_matrix, 
         color = color_map, 
         cluster_rows = TRUE, 
         cluster_cols = TRUE, 
         fontsize = 10, 
         main = "Variable Correlation Heatmap")

In this example, we first define a custom color mapping function ranging from blue to red using colorRampPalette. Next, within the pheatmap function, we enable the cluster_rows and cluster_cols parameters. This will automatically calculate dendrograms for rows and columns based on distance matrices and sort the data accordingly. This automated sorting feature is crucial for identifying potential patterns in the data because it reduces visual noise, making key correlation structures immediately apparent. Additionally, we can easily add row names, column names, and custom titles to make the chart more professional.

Advanced Techniques: Integrating Grid Lines with Custom Styles

To increase information density and avoid overly blurred colors, we can introduce grid lines to separate different data blocks or categories. This is particularly useful when handling datasets that contain a mix of categorical and numerical variables. Furthermore, adjusting the alpha (transparency) parameter and border color can further enhance chart readability.

In pheatmap, these effects can be achieved by setting parameters such as show_rownames, show_colnames, and border_color. For instance, if a heatmap is used to display gene expression data, row names typically represent Gene IDs while column names represent Sample IDs; in this case, clear grid lines help distinguish between different sample groups.

pheatmap(data_matrix, 
         color = color_map, 
         cluster_rows = TRUE, 
         show_rownames = TRUE, 
         show_colnames = TRUE, 
         border_color = NA, 
         fontsize_row = 8, 
         fontsize_col = 8)

Note that setting border_color to NA removes the borders between cells, resulting in smoother color transitions. If grid lines need to be retained to distinguish categories, border_color can be set to a specific color value. Additionally, adjusting font size is equally important for ensuring readability when dealing with large amounts of labels (such as hundreds of genes). Through these fine-tunings, the heatmap transforms from being merely a simple matrix of colors into a precise dashboard capable of carrying complex statistical information.

Mastering heatmap plotting techniques in R language is an essential component of data analysts' exploratory data analysis (EDA) workflow. Whether utilizing ggridges for rapid prototyping or leveraging pheatmap for deep exploration, these tools enable us to reveal the stories hidden behind the data with intuitive clarity.