ggplot2绘制相关矩阵热图:变量排序及绘图问题求助
Got it, let's put together a complete, reproducible solution for your correlation heatmap with clustering-ordered variables using ggplot2. Here's a step-by-step breakdown you can adapt to your data:
Step 1: Load Required Packages
First, install and load the tools we'll need for correlation calculation, data reshaping, and plotting:
# Install packages if you haven't already install.packages(c("ggplot2", "reshape2", "Hmisc", "dplyr")) # Load libraries library(ggplot2) library(reshape2) library(Hmisc) library(dplyr)
Step 2: Prepare Your Data
We'll use the built-in mtcars dataset as a working example—replace this with your actual data frame.
# Replace mtcars with your own data frame data <- mtcars
Step 3: Compute the Correlation Matrix
Use rcorr() to calculate Pearson correlations (add type = "spearman" inside the function if you need rank-based correlations instead):
# Generate correlation matrix (extract only the correlation values with $r) cormatx <- rcorr(as.matrix(data))$r
Step 4: Reorder Variables via Hierarchical Clustering
This step ensures variables are sorted by their correlation similarity:
# Convert correlation values to a distance metric (0 = perfect correlation, 1 = no correlation) dist_matrix <- as.dist((1 - cormatx)/2) # Perform hierarchical clustering cluster_hcl <- hclust(dist_matrix) # Reorder the correlation matrix using the cluster order cormatx_ordered <- cormatx[cluster_hcl$order, cluster_hcl$order]
Step 5: Reshape to Long Format for ggplot
We need to convert the square matrix into a long data frame. Crucially, we'll set factor levels to preserve the cluster order (so ggplot doesn't reorder variables alphabetically):
# Melt the ordered matrix into long format melted_cormatx <- melt(cormatx_ordered, na.rm = TRUE) # Lock in the cluster order for x and y axes melted_cormatx <- melted_cormatx %>% mutate( Var1 = factor(Var1, levels = rownames(cormatx_ordered)), Var2 = factor(Var2, levels = colnames(cormatx_ordered)) )
Step 6: Build the Heatmap with ggplot2
This final code creates a clean, informative heatmap with correlation values, a color gradient, and readable axes:
ggplot(melted_cormatx, aes(x = Var1, y = Var2, fill = value)) + # Create heatmap tiles with white borders geom_tile(color = "white") + # Add rounded correlation values to each tile geom_text(aes(label = round(value, 2)), color = "black", size = 3) + # Color gradient: blue for negative correlations, red for positive, white at 0 scale_fill_gradient2( low = "#0072B2", mid = "white", high = "#D55E00", midpoint = 0, limit = c(-1, 1), space = "Lab", name = "Pearson\nCorrelation" ) + # Clean up the theme for readability theme_minimal() + theme( axis.text.x = element_text(angle = 45, vjust = 1, size = 10, hjust = 1), axis.title.x = element_blank(), axis.title.y = element_blank(), panel.grid.major = element_blank(), panel.border = element_blank(), panel.background = element_blank(), axis.ticks = element_blank(), legend.justification = c(1, 0), legend.position = c(0.6, 0.7), legend.direction = "horizontal" ) + # Ensure tiles are square-shaped coord_fixed()
Quick Customization Tips:
- Missing Values:
rcorr()automatically handles NA values with pairwise deletion—no extra steps needed. - Color Scheme: Swap out the
low/highhex codes to match your preferred color palette. - Text Size: Adjust the
sizeargument ingeom_text()to make correlation values larger or smaller.
内容的提问来源于stack exchange,提问作者Sophie

