如何在ggplot2的相关性热图中添加柱状图?
Yes, you can achieve this by combining your correlation heatmap with a bar plot (using VIF values from your dataset) using ggplot2 and cowplot for alignment. Here's how:
Step 1: Load Required Libraries
library(tidyverse) library(ggplot2) library(cowplot)
Step 2: Prepare Data for Bar Plot
Extract unique variable-VIF pairs (since VIF values are consistent for each variable):
bar_data <- melted_cormat %>% distinct(Var2, vif) %>% mutate(variable = Var2)
Step 3: Create the Correlation Heatmap
Adjust the original heatmap with minor theme tweaks for better alignment:
heatmap_plot <- ggplot(data = melted_cormat, aes(Var2, Var1, fill = value))+ geom_tile(color = "white")+ scale_fill_gradient2(low = "#2bc290", high = "#b6c1ff", mid = "#F9F7F5", midpoint = 0, limit = c(-1,1), space = "Lab", name="Magnitude of\nCorrelation") + theme_minimal()+ theme(axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1), axis.text.y = element_text(size = 12), plot.margin = margin(5, 5, 5, 5))+ coord_fixed()+ xlab("") + ylab("")
Step 4: Create the Vertical Bar Plot
Align the bar plot to match the heatmap's y-axis:
bar_plot <- ggplot(bar_data, aes(x = vif, y = Var2))+ geom_col(fill = "#6366F1", width = 0.7)+ scale_x_continuous(expand = c(0,0))+ theme_minimal()+ theme(axis.text.y = element_blank(), axis.title.y = element_blank(), axis.text.x = element_text(size = 10), axis.title.x = element_text(size = 12, label = "VIF"), plot.margin = margin(5, 5, 5, 0))+ coord_fixed(ratio = 0.5) # Adjust ratio to match heatmap height
Step 5: Combine Plots
Merge the heatmap and bar plot side by side:
combined_plot <- plot_grid(heatmap_plot, bar_plot, ncol = 2, rel_widths = c(1, 0.3)) print(combined_plot)
This produces a layout where the correlation heatmap sits on the left, and a vertical bar plot showing VIF values for each variable is on the right—matching the style of your example. You can tweak the rel_widths parameter to adjust the bar plot's relative size, or change the bar fill color to match your heatmap's palette.
If you prefer the bar plot below the heatmap, replace ncol = 2 with nrow = 2 and use rel_heights instead of rel_widths.
内容的提问来源于stack exchange,提问作者lola

