如何使用R语言ggplot包可视化目标向量与数据框各列的相关系数
ggplot可视化相关系数的具体实现
首先需要把计算得到的宽格式相关系数结果转换为ggplot支持的长数据格式,以下代码可直接复现全流程:
library(tidyverse) # --------------- 数据准备(你已完成的步骤,可直接替换为真实数据)--------------- set.seed(123) # 仅用于结果复现,跑真实数据时可删除 y1 = rpois(10,3) y2 = rpois(10,5) y3 = rpois(10,10) y4 = rpois(10,20) data = tibble(y1,y2,y3,y4) xx = rpois(10,4) # 计算相关系数并转长格式,是绘图的必要前置步骤 cor_df <- data %>% dplyr::summarize(across(.cols = everything(), ~ cor(.x,xx, use = "pairwise.complete.obs"))) %>% pivot_longer(cols = everything(), names_to = "var_name", values_to = "cor_coef")
以下提供3种常用的可视化方案,所有方案都固定相关系数色阶范围为[-1,1],避免色阶自适应导致的视觉误判。
方案1:水平条形图(可读性最高,首推)
正负相关方向、数值大小辨识度最高,适合正式分析报告使用:
ggplot(cor_df, aes(x = reorder(var_name, cor_coef), y = cor_coef, fill = cor_coef)) + geom_col(width = 0.65) + # 直接在条形上标注相关系数数值,自动适配正负方向的标注位置 geom_text(aes(label = round(cor_coef, 3), hjust = ifelse(cor_coef >= 0, -0.2, 1.2)), size = 4) + # 用红-白-蓝渐变区分负相关、零相关、正相关,符合统计可视化惯例 scale_fill_gradient2(low = "#d73027", mid = "white", high = "#4575b4", midpoint = 0, limits = c(-1, 1), name = "相关系数") + geom_hline(yintercept = 0, color = "grey30", linewidth = 0.8) + coord_flip() + labs(x = "数据框变量", y = "与目标向量xx的相关系数", title = "各变量与xx的相关系数") + theme_minimal() + theme(plot.title = element_text(hjust = 0.5))
方案2:单行热图
适合和其他多变量热图拼接、统一排版使用:
ggplot(cor_df, aes(x = var_name, y = "相关系数", fill = cor_coef)) + geom_tile(color = "white", linewidth = 1) + geom_text(aes(label = round(cor_coef, 3)), size = 4) + scale_fill_gradient2(low = "#d73027", mid = "white", high = "#4575b4", midpoint = 0, limits = c(-1, 1), name = "相关系数") + labs(x = "变量", y = NULL, title = "相关系数热图") + theme_minimal() + theme(plot.title = element_text(hjust = 0.5), panel.grid = element_blank())
方案3:棒棒糖散点图
样式更简洁,点的大小和颜色同时映射相关系数大小:
ggplot(cor_df, aes(x = var_name, y = cor_coef, color = cor_coef, size = abs(cor_coef))) + geom_segment(aes(x = var_name, xend = var_name, y = 0, yend = cor_coef), color = "grey60") + geom_point() + geom_text(aes(label = round(cor_coef, 3), vjust = ifelse(cor_coef >= 0, -1, 1.5)), size = 3.5, color = "black") + scale_color_gradient2(low = "#d73027", mid = "white", high = "#4575b4", midpoint = 0, limits = c(-1, 1)) + geom_hline(yintercept = 0, color = "grey30", linewidth = 0.8) + scale_size_continuous(range = c(2,6)) + labs(x = "变量", y = "与xx的相关系数", title = "相关系数散点图") + theme_minimal() + theme(plot.title = element_text(hjust = 0.5), legend.position = "none")
小提示:如果需要调整配色、字体、标注样式,直接修改对应geom的参数即可。
内容的提问来源于stack exchange,提问作者Homer Jay Simpson
相关产品推荐
相关产品推荐

