如何将R语言pheatmap绘制的热力图行名显示在左侧?
Great question! You’re right that pheatmap doesn’t have a built-in parameter like row_names_side = "left" (unlike base R’s heatmap()), but since pheatmap relies on the grid graphics system, we can tweak the underlying graphic table (gtable) to reposition the row names manually.
Here’s a step-by-step solution to adjust your existing code:
Step 1: Generate your base heatmap
First, run your original code to create the heatmap object—this gives us the gtable we’ll modify later:
# Color palette for the heatmap colors = c(seq(-5,-1,length=1000),seq(-.999999,.999999,length=1000),seq(1, 5,length=1000)) my_palette <- colorRampPalette(c("blue", "white", "red"))(n = 2999) data.random <- data.frame(matrix(data=rnorm(150), ncol=15, nrow=10)) rownames(data.random) <- letters[1:10] colnames(data.random) <- LETTERS[1:15] # Create the base heatmap object h <- pheatmap(data.random, cluster_rows=FALSE, cluster_cols=FALSE, legend=TRUE, color=my_palette, breaks=colors, show_rownames=TRUE, show_colnames=TRUE )
Step 2: Modify the gtable to shift row names left
We’ll adjust the layout of the gtable returned by pheatmap to move row names to the left and reposition the heatmap body to avoid overlap:
library(grid) library(gtable) # Extract the gtable from the pheatmap output g <- h$gtable # Locate the row name element in the gtable layout row_names_idx <- which(g$layout$name == "row_names") # Move row names to the left: adjust their position and alignment g$grobs[row_names_idx][[1]]$hjust <- 1 # Align text to the right of their space (so it sits next to the heatmap) g$layout[row_names_idx, ]$l <- 1 # Shift row names to the first column of the gtable # Shift the main heatmap body right to make space for left-aligned row names heatmap_body_idx <- which(g$layout$name == "matrix") g$layout[heatmap_body_idx, ]$l <- g$layout[heatmap_body_idx, ]$l + 1 # Render the modified heatmap grid.newpage() grid.draw(g)
What this does:
- We extract the
gtable(the underlying structure of the plot) from thepheatmapoutput. - We find the row name element and move it to the first column of the layout, adjusting text alignment so it sits neatly next to the heatmap.
- We shift the main heatmap matrix one column to the right to avoid overlapping with the now left-positioned row names.
- Finally, we use
grid.draw()to display the adjusted plot.
This will produce the exact same heatmap as your original code, but with row names displayed on the left instead of the right.
内容的提问来源于stack exchange,提问作者Koalabear

