How to Make a Heatmap in R

How to Make a Heatmap in R

In this tutorial, you will learn how to make a heatmap in R using ggplot2. A heatmap uses colors to represent numerical values, making it easier to identify patterns in a dataset. For example, we can use a heatmap to visualize correlations between variables and see which relationships are positive, negative, or close to zero.

In psychological research, we often work with several related variables, such as personality traits, cognitive abilities, or questionnaire items. A correlation matrix can help us understand how these variables relate, but it becomes difficult to interpret as the number of variables increases. A heatmap provides a visual way to examine the same information.

In this example, we will use data from the psych package to examine correlations between personality questionnaire items. First, we will prepare the data and calculate a correlation matrix. Then, we will use ggplot2 to create a heatmap showing the correlations between the items. Finally, we will adjust the colors and appearance of the plot to make it easier to read.

Preparing the Data for a Heatmap in R

Before creating a heatmap in R, we need some numerical data. In this example, we will use the bfi dataset from the psych package. The dataset contains responses from 2,800 participants to 25 personality items from the Big Five Inventory (BFI), along with three demographic variables.

The personality items measure five dimensions: Agreeableness, Conscientiousness, Extraversion, Neuroticism, and Openness. Each dimension has five items.

We will use the individual personality items to create a correlation heatmap. First, load the psych package and the dataset.

Here is how to do it in R:

# load the package
library(psych)
# load the data
data(bfi)Code language: R (r)

Next, we will select the 25 personality items. We do not need the demographic variables for this example. We will also remove observations with missing values in any of the selected items.

# Select only the personality item columns
bfi_traits <- bfi %>%
  select(A1:A5, C1:C5, E1:E5, N1:N5, O1:O5)

# Remove rows with any missing values in the selected columns
bfi_clean <- na.omit(bfi_traits)Code language: CSS (css)

In the code above, we used select() from the dplyr package to select the five items belonging to each personality dimension. We then used na.omit() to remove rows with missing values in the selected columns.

Now that we have prepared our data, we can calculate the correlations between the personality items.

# Compute the correlation matrix
cor_matrix <- cor(bfi_clean)Code language: R (r)

We used cor() to calculate a correlation matrix from our cleaned dataset. By default, this function calculates Pearson correlation coefficients. The resulting matrix contains the correlations between all 25 personality items.

Each correlation coefficient ranges from -1 to 1. Positive values indicate that two items tend to increase together, while negative values indicate that higher scores on one item tend to be associated with lower scores on the other. Values close to zero indicate little or no linear relationship. Next, we will use this correlation matrix to create a heatmap.

If you want to learn more about calculating correlations and creating correlation matrices in R, you can read the following tutorials:

Creating a Heatmap in R

Now that we have calculated the correlation matrix, we can use ggplot2 to create a heatmap in R. In our example, we have 25 personality items, which means that the correlation matrix contains 625 values. A heatmap makes it easier to examine these correlations and identify patterns that might be difficult to see in a table.

Before creating the plot, however, we need to reshape the correlation matrix into a format that works with ggplot2. We will also remove the upper triangle of the matrix because it contains the same correlations as the lower triangle.

Step 1: Transforming the Data

First, we will convert our correlation matrix into long format and keep only the lower triangle.

# Convert the correlation matrix to long format
cor_long <- as.data.frame(as.table(cor_matrix)) %>%
  filter(as.numeric(factor(Var1)) >= as.numeric(factor(Var2)))Code language: R (r)

In the code above, we used as.table() and as.data.frame() to convert the correlation matrix into a dataframe with three columns: Var1, Var2, and Freq. The first two columns identify the personality items, while Freq contains their correlation coefficients.

Next, we used filter() to keep the lower triangle of the matrix, including the diagonal. Since the correlation between two items is the same regardless of their order, we only need to display each pair once. The diagonal contains correlations of 1 because each item is perfectly correlated with itself. We will keep these values in our heatmap.

Step 2: Creating the Heatmap

Now that our data are in long format, we can create the heatmap using ggplot2.

ggplot(cor_long, aes(Var1, Var2, fill = Freq)) +
  geom_tile(color = NA) +  # No border/grid lines between tiles
  scale_fill_gradient2(low = "blue", mid = "white", high = "red", midpoint = 0,
                       name = "Correlation") +
  labs(title = "Correlation Heatmap of BFI Personality Traits",
       x = "", y = "") +
  theme_minimal() +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1),
    panel.grid = element_blank()  # Removes gridlines
  )Code language: R (r)

In the code above, we passed cor_long to ggplot() and mapped the personality items to the x- and y-axes. We then used geom_tile() to create a tile for each correlation coefficient. The fill argument determines the color of each tile based on the correlation value.

We used scale_fill_gradient2() to create a color scale centered at zero. Negative correlations are shown in blue, positive correlations in red, and values close to zero in white. Stronger correlations are represented by more intense colors.

Finally, we used theme_minimal() to give the plot a simple appearance. We also rotated the x-axis labels by 45 degrees to make the item names easier to read and removed the background grid lines using panel.grid = element_blank().

Here is what our heatmap looks like:

heatmap created in R with ggplot2

Interpreting the Heatmap

We can now use the heatmap to examine how the personality items are related. For example, red tiles indicate positive correlations, meaning that participants who score higher on one item also tend to score higher on the other. Blue tiles indicate negative correlations, meaning that higher scores on one item tend to be associated with lower scores on the other. We can also look for groups of items with similar correlation patterns. Since the BFI includes items measuring five personality dimensions, we might expect items within the same dimension to correlate with each other.

However, we should remember that the heatmap shows correlations between individual questionnaire items, not correlations between the five personality dimensions themselves. To examine correlations between the dimensions, we would first need to calculate scale scores.

The heatmap provides a useful overview of the relationships between the items, but we would need to examine the correlation coefficients more closely to determine the strength of specific relationships.

Summary: How to Make a Heatmap in R

In this tutorial, you learned how to make a heatmap in R using ggplot2. We used the bfi dataset from the psych package to examine correlations between personality questionnaire items. We started by selecting the personality items, removing missing values, and calculating a correlation matrix using cor(). Next, we converted the matrix into long format and removed the upper triangle to avoid displaying duplicate correlations.

Finally, we used ggplot2 to create a heatmap showing the relationships between the items. We also adjusted the colors, removed the grid lines, and rotated the axis labels to make the plot easier to read. Heatmaps can be useful when working with several related variables, particularly when we want to identify patterns that might be difficult to see in a correlation matrix.

I hope you found this tutorial helpful. If you have any questions about creating heatmaps in R, feel free to leave a comment below.

Resources

Here are some more data visualization tutorials that you might find helpful:

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top