如何叠加两个corrplot.mixed图形:上下部分分别展示数值与椭圆?
Combine Two corrplot.mixed Plots for Pre/Post Correlation Matrices
Hi Mattia, awesome first question on Stack Overflow! I’ve got a practical R solution to help you overlay those two correlation plots exactly how you described—showing both correlation values in the lower triangle and comparing ellipses in the upper triangle. Let’s dive in:
Step 1: Prepare Your Environment & Data
First, make sure you’ve got the corrplot package installed and loaded. We’ll start with sample data (swap this out with your actual corr.pre and corr.post matrices):
# Install if needed: install.packages("corrplot") library(corrplot) # Create sample pre/post correlation matrices (replace with your data!) set.seed(123) corr.pre <- cor(matrix(rnorm(50), ncol = 5)) corr.post <- cor(matrix(rnorm(50, mean = 0.2), ncol = 5))
Step 2: Build the Combined Plot
We’ll layer two plots together: first the post-period ellipses, then overlay the pre-period ellipses in a distinct color. Finally, we’ll add both correlation values to the lower triangle:
# 1. Base plot: Post-period ellipses in upper triangle, blank lower triangle corrplot.mixed( corr.post, upper = "ellipse", lower = "blank", upper.col = colorRampPalette(c("#2c3e50", "#ffffff", "#e74c3c"))(100), tl.pos = "lt", # Position variable labels at top-left tl.cex = 0.8, # Adjust label size if needed cl.pos = "r" # Keep color bar on right ) # 2. Overlay pre-period ellipses in a darker, distinct color corrplot( corr.pre, add = TRUE, type = "upper", method = "ellipse", col = colorRampPalette(c("#16a085", "#ffffff", "#c0392b"))(100), bg = "transparent", tl.pos = "n", # Hide duplicate labels cl.pos = "n" # Hide duplicate color bar ) # 3. Add both pre/post correlation values to the lower triangle n <- nrow(corr.pre) for (i in 2:n) { for (j in 1:(i - 1)) { # Calculate position coordinates (matches corrplot's grid) x <- j y <- n - i + 1 # Add pre-period value (bottom of cell, dark teal) text(x, y - 0.18, round(corr.pre[i, j], 2), cex = 0.7, col = "#16a085") # Add post-period value (top of cell, dark red) text(x, y + 0.18, round(corr.post[i, j], 2), cex = 0.7, col = "#c0392b") } } # 4. Add legend to clarify pre/post periods legend( "bottomright", legend = c("Pre-period", "Post-period"), col = c("#16a085", "#c0392b"), lwd = 3, cex = 0.8, bty = "n" # Remove legend box for cleaner look )
Key Tips for Customization
- Match Matrix Dimensions: Double-check that
corr.preandcorr.posthave the same number of variables in the same order—otherwise the overlay will be misaligned! - Adjust Colors: Swap out the hex codes for any color palette that works better for your data (try
RColorBrewerpalettes for professional options). - Tweak Text: Modify
round()to change decimal places, or adjustcexto make the correlation values larger/smaller. - Label Placement: If variable names are too long, use
tl.rot = 45to rotate labels in the base plot.
内容的提问来源于stack exchange,提问作者Mattia Palese




