Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To create a ggplot2 heatmap that has a vector for the heatmap located at the bottom and a vector for the values located on the side, you can use the ggheatmap() function from the ggpubr package.

Here is an example code:

library(ggpubr) library(dplyr) # creating a matrix with random values set.seed(123) mat <- matrix(sample(1:50, 15), ncol = 3, nrow = 5) # creating a data.frame with the row and column indices df <- expand.grid(row = 1:nrow(mat), col = 1:ncol(mat)) df$value <- as.vector(mat) # creating the heatmap ggheatmap(df, x = "col", y = "row", color = "value", ylim = c(0.5, nrow(mat) + 0.5), xlab = "Column", ylab = "Row", font.label = list(size = 12, color = "black"), font.main = list(size = 14, color = "black"), legend.title = "Value", legend.label.size = 12, heatmap_width = unit(5, "cm"), heatmap_height = unit(5, "cm")) + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) + annotate("text", x = seq_along(mat), y = rep(0.3, ncol(mat)), label = seq_along(mat), color = "black", fontface = "bold") + annotate("text", x = rep(0.3, nrow(mat)), y = seq_along(mat), label = LETTERS[1:nrow(mat)], color = "black", fontface = "bold") + scale_fill_gradient(low = "white", high = "blue") + guides(fill = guide_colorbar(title.position = "top", title.vjust = 1, label.position = "top", label.vjust = 0.5, nbin = 10)) 

In this code, we first create a matrix mat with random values. We then convert it into a data frame df with the row and column indices and the corresponding values.

We then use the ggheatmap() function with the color argument set to "value" to create the heatmap. We also set the x and y arguments to "col" and "row", respectively, to indicate the column and row indices in the data frame.

To create the vectors for the heatmap and values, we use the annotate() function to add text labels to the plot. We also rotate the x-axis labels by 90 degrees using the theme() function.

Finally, we use the scale_fill_gradient() function and the guides() function to set the color scale and the color bar legend, respectively.