如何在R中用ggscatter将带置信区间的两个相关散点图画在同一张图
解决方案:在同一张图中绘制两组带置信区间的Spearman相关散点图
1. 合并两组数据并绘制同图
要把两组数据的散点、回归线及置信区间放在同一张图,核心是先将数据整理为长格式(tidy data),再利用ggscatter的分组映射功能实现。
步骤1:整理数据
将四个独立向量合并为包含分组信息的数据框:
library(tidyverse) library(ggpubr) # 生成示例数据(设置随机种子保证结果可复现) set.seed(123) spentWithTool <- sample(1:7, 20, replace = TRUE) understoodWithTool <- sample(1:5, 20, replace = TRUE) spentWithoutTool <- sample(1:4, 10, replace = TRUE) understoodWithoutTool <- sample(1:5, 10, replace = TRUE) # 转换为长格式数据框 merged_data <- tibble( 时间花费 = c(spentWithTool, spentWithoutTool), 理解程度 = c(understoodWithTool, understoodWithoutTool), 组别 = rep(c("使用工具", "未使用工具"), c(20, 10)) )
步骤2:绘制合并图
利用ggscatter的分组参数,同时添加回归线、置信区间及Spearman相关系数:
ggscatter(merged_data, x = "时间花费", y = "理解程度", color = "组别", # 按组别区分颜色 palette = c("darkred", "darkblue"), # 指定两组颜色 add = "reg.line", # 添加回归线 add.params = list(color = c("red", "blue")), # 回归线颜色 conf.int = TRUE, # 添加置信区间 conf.int.level = 0.95 # 置信区间水平 ) + # 分别标注两组的Spearman相关系数(调整位置避免重叠) stat_cor(aes(color = 组别), method = "spearman", label.x = c(2, 5), label.y = c(5, 1))
这段代码会生成一张整合图,包含两组散点、对应颜色的回归线及置信区间,同时标注各自的Spearman相关系数。
2. 关于是否可以不转数据框使用ggscatter
不行。ggscatter是基于ggplot2的封装函数,而ggplot2要求输入数据必须是数据框(或tibble)格式,无法直接使用独立向量作为输入。因此必须将向量组合成数据框后才能使用ggscatter。
内容的提问来源于stack exchange,提问作者DeveloperInTraining
相关产品推荐
相关产品推荐

