You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在ggplot2中基于group变量为回归模型散点着色的技术求助

解决方案

要实现按group变量为散点着色,核心是把原始数据中的group变量关联到添加变量图的数据集里,再在ggplot中设置颜色映射。以下是修改后的代码,关键改动已标注:

修改后的完整代码

#create function for partial regression plots
avPlots.invis <- function(MODEL, ...) {
  ff <- tempfile();
  png(filename = ff);
  OUT <- car::avPlots(MODEL, ...);
  dev.off()
  unlink(ff);
  OUT; }

ggAVPLOTS  <- function(MODEL, YLAB = NULL) {
 #Extract the information for AV plots
  AVPLOTS <- avPlots.invis(MODEL);
  K       <- length(AVPLOTS);
  # 提取原始数据中的group变量(保留行名用于匹配)
  original_group <- MODEL$model$group
  names(original_group) <- rownames(MODEL$model)
  
  #Create the added variable plots using ggplot
  GGPLOTS <- vector('list', K);
  for (i in 1:K) {
  DATA         <- data.frame(AVPLOTS[[i]]);
  # 把group变量合并到当前绘图数据中(通过行名匹配)
  DATA$group <- original_group[rownames(DATA)]
  
  GGPLOTS[[i]] <- ggplot2::ggplot(aes_string(x = colnames(DATA)[1],
                                             y = colnames(DATA)[2],
                                             color = "group"),  # 新增:将group映射为颜色
                                 data = DATA) +
                  geom_point(shape = 19) +  # 移除固定colour,改用映射
                  geom_smooth(method = 'lm', se = FALSE,
                              color = '#000000', formula = y ~ x, linetype = 'solid') +
                  # 可选:自定义group的颜色
                  scale_color_manual(values = c("control" = "#1f77b4", "participant" = "#ff7f0e")) +
                  ggtitle("A") +
                  theme(plot.title = element_text(lineheight=1, face="bold", size=18), 
                        axis.text=element_text(colour="black", size=12), 
                        axis.title = element_text(face="bold", colour="black", size = 12),
                        legend.position = "right") +  # 调整图例位置
                  xlim(-2, 3) +
                  ylim (-20, 20) +
                  xlab("Total PA (adjusted)") +
                  ylab("Fluid Intelligence Score"); }
  #Return output object
  GGPLOTS; }

p1 <- ggAVPLOTS(model4)
tiff("Model4 fluid-totalPA.tiff", height = 600, width = 600)
print(p1[1])  # 补充print确保图像输出
dev.off()  # 关闭绘图设备

关键改动说明

  • 关联group变量:从模型的MODEL$model中提取原始group变量,利用行名与AVPLOTS数据的行名匹配,将group合并到每个绘图数据集DATA中。
  • 颜色映射:在ggplot的aes_string中添加color = "group",把group变量映射为点的颜色,同时移除geom_point里的固定colour参数。
  • 自定义颜色(可选):用scale_color_manual为control和participant设置专属颜色,让类别区分更直观。
  • 修复绘图输出:在tiff设备中添加print(p1[1])和dev.off(),确保图像正确保存。

该改动不会破坏原有代码的整体结构,同时实现了按group着色的需求。

内容的提问来源于stack exchange,提问作者Nic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 16:21:01