使用R绘制带聚类的热图:聚类、配色及单元格尺寸优化求助
Hey there! Let's tackle your heatmap issues one by one—clustering similar data patterns, improving color schemes, and adjusting cell sizes. Here's how you can tweak your current code and add those features:
ggplot2 doesn’t handle clustering automatically, so we’ll first sort your rows and columns based on hierarchical clustering to group similar data together. Here’s how to modify your workflow:
library(ggplot2) library(reshape2) # Load and prepare data mydata <- read.table("Test_data", sep="\t", header=TRUE) # Convert to matrix for clustering (assuming first column is 'ID') data_matrix <- as.matrix(mydata[, -1]) rownames(data_matrix) <- mydata$ID # Perform hierarchical clustering for rows (IDs) row_clust <- hclust(dist(data_matrix)) row_order <- row_clust$order # Perform hierarchical clustering for columns (variables) col_clust <- hclust(dist(t(data_matrix))) col_order <- col_clust$order # Reorder data based on clustering results mydata_clustered <- mydata[row_order, c(1, col_order + 1)] # Melt and normalize as before melted_cormat <- melt(mydata_clustered) melted_cormat$new <- log2(1 + melted_cormat$value)
This reorders your rows and columns so entries with similar patterns are grouped together.
The default ggplot2 color gradient is often lackluster. Try these color-blind friendly, visually appealing alternatives:
Option 1: Viridis Palette (Recommended)
Viridis palettes are designed to be accessible and look great for continuous data:
ggplot(data = melted_cormat, aes(x=variable, y=ID, fill=new)) + geom_tile() + scale_fill_viridis_c(option = "plasma", name = "Log2(1+Value)") # Customize legend title
You can swap option with other values like "viridis", "magma", "inferno", or "cividis" to find your favorite.
Option 2: Diverging Palette (If you have positive/negative values)
If your normalized data has both high and low extremes, a diverging palette works well:
ggplot(data = melted_cormat, aes(x=variable, y=ID, fill=new)) + geom_tile() + scale_fill_gradient2( low = "#2c7fb8", mid = "#ffffcc", high = "#d95f02", midpoint = median(melted_cormat$new), name = "Log2(1+Value)" )
To make cells larger and avoid cramped labels, use these adjustments:
ggplot(data = melted_cormat, aes(x=variable, y=ID, fill=new)) + geom_tile() + scale_fill_viridis_c(option = "plasma", name = "Log2(1+Value)") + # Adjust axis text to prevent overlap and give cells more space theme( axis.text.x = element_text(angle = 45, hjust = 1, size = 10), axis.text.y = element_text(size = 10), plot.margin = margin(1, 1, 1, 1, "cm") # Add extra margin around the plot ) + # Keep cells square (adjust ratio if you want rectangular cells) coord_fixed(ratio = 1)
Bonus: Export High-Resolution Heatmap
When saving your plot, specify larger dimensions to ensure cells are clear:
ggsave("my_heatmap.png", width = 14, height = 10, dpi = 300)
Play around with the width/height values to get the perfect cell size for your dataset!
内容的提问来源于stack exchange,提问作者Shrilaxmi M S

