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

如何在ggplot回归模型中为额外因子添加形状并调整回归线、R²标注及图例

解决方案

下面是满足你所有需求的修改后代码:

library(ggpubr)
data(iris)
iris$ran <- as.factor(rep(c(1:2), each = 75))
fit <- lm(Sepal.Length ~ Petal.Width+Species+ran, data = iris)

ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1], 
                             color=names(fit$model)[3], shape=names(fit$model)[4])) + 
  geom_point() + 
  # 仅按Species拟合回归线,移除覆盖分组颜色的冗余参数
  geom_smooth(aes_string(fill = names(fit$model)[3], color = names(fit$model)[3]), 
              method = "lm", fullrange = TRUE) + 
  # 用bquote实现R²上标格式,同时保留动态统计值
  labs(x=expression(paste("Petal Width")), y=expression(paste("Sepal Length")), 
       caption = bquote(R^2 == .(signif(summary(fit)$r.squared, 2)) ~ "\t" ~ 
                         "Adj"~R^2 == .(signif(summary(fit)$adj.r.squared, 2)) ~ "\t" ~
                         "Intercept =" ~ .(signif(fit$coef[[1]],2 )) ~ "\t" ~
                         "Slope =" ~ .(signif(fit$coef[[2]], 2)) ~ "\t" ~
                         "P =" ~ .(signif(summary(fit)$coef[2,4], 2)))) + 
  # 自定义ran因子的图例名称和水平标签
  scale_shape_discrete(name = "Random", labels = c("Factor1", "Factor2")) +
  theme_classic2(base_size = 14)

关键修改说明

  • 仅按Species生成回归线:
    删掉了geom_smooth里的col="red"参数(这个参数会强制所有回归线为红色,覆盖Species的分组颜色),同时确保geom_smooth的映射只绑定Species,完全不涉及ran因子,这样就只会为每个Species拟合一条回归线。
  • R²上标格式:
    用bquote()函数构建标注文本,R^2会被渲染为上标样式的R²,通过.()语法可以把动态计算的统计值嵌入到表达式中,兼顾格式和数据准确性。
  • 修改ran因子的图例与标签:
    添加scale_shape_discrete()函数,通过name参数把图例标题改成"Random",labels参数把原有的1、2替换成你需要的"Factor1"和"Factor2"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:47:37