How to create a heat map on R programming? Heat maps are a graphical representation of data that uses color coding to show the values of a matrix. They are useful for visualizing large amounts of data and identifying patterns and trends. This article will show you how to create a heat map in R programming. To create a heat map in R, we will use the heatmap() function, which is part of the base R package. We will also use the scale() function to normalize the data so that the colors represent the relative values of the matrix.
Here are the steps to create a heat map in R:
Step 1: Prepare your data
The data for your heat map should be in a matrix format, with rows and columns representing variables and the values representing the observations. Here is an example of a matrix:
data <- matrix(c(10, 20, 30, 40, 50, 60, 70, 80, 90), nrow = 3, ncol = 3)
Step 2: Normalize the data
We will use the scale()
function to normalize the data so that the colors represent the relative values of the matrix. This is done by subtracting the mean and dividing by the standard deviation of each row or column:
scaled_data <- scale(data, center = TRUE, scale = TRUE)
Step 3: Create the heat map
To create the heat map, we will use the heatmap()
function. Here is the code:
heatmap(scaled_data, col = rev(heat.colors(10)), margins = c(5, 10))
The scaled_data
argument is the matrix of normalized data. The col
argument specifies the color palette to use. In this case, we are using the heat.colors()
function to generate a palette of 10 colors, which we reverse with the rev()
function so that higher values are darker. The margins
argument specifies the size of the margins around the heat map.
Step 4: Add labels to the heat map
To add labels to the heat map, we can use the xlab
, ylab
, and main
arguments. Here is an example:
heatmap(scaled_data, col = rev(heat.colors(10)), margins = c(5, 10),
xlab = "Columns", ylab = "Rows", main = "Heat Map Example")
The xlab
argument specifies the label for the x-axis, the ylab
argument specifies the label for the y-axis, and the main
argument specifies the main title of the heat map.
Step 5: Customize the heat map
There are many ways to customize the heat map in R. For example, you can change the font size and color of the labels, adjust the size of the heat map, and add a color scale legend. Here is an example of how to change the font size and color of the labels:
heatmap(scaled_data, col = rev(heat.colors(10)), margins = c(5, 10), xlab = "Columns", ylab = "Rows", main = "Heat Map Example", cex.axis = 1.5, col.axis = "white")
The cex.axis
argument specifies the font size of the axis labels, and the col.axis
argument specifies the color of the axis labels.
Comments are closed.