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

如何在R语言绘制的回归散点图中添加R²值

在R语言散点图中添加R²值的方法

针对你提供的线性回归绘图代码,有两种常用方法可以在散点图上添加R²值:

方法一:使用基础绘图系统

直接在现有代码基础上添加提取R²和文本标注的步骤即可,优化后的完整代码如下:

# 读取数据
POI <- read.csv(file="PeaksOfInterest_MassRemaining.csv", header = TRUE)

# 构建回归模型(简化写法,无需重复写POI$)
model.1080 <- lm(Mass_Remaining ~ Wavenumber_1080, data=POI)

# 绘制回归诊断图
plot(model.1080)

# 查看模型摘要
summary(model.1080)

# 绘制散点图
plot(POI$Wavenumber_1080, POI$Mass_Remaining, 
     col='red', 
     main='Summary of Regression Model 1080', 
     xlab='Intensities at Wavenumber 1080', 
     ylab='Mass Remaining')

# 添加拟合线(直接用已构建的模型,无需重新拟合)
abline(model.1080, col="blue")  

# 提取并格式化R²值
r_squared <- summary(model.1080)$r.squared
r_squared_text <- paste0("R² = ", round(r_squared, 3))

# 将R²添加到散点图的右上角位置(可根据需求调整x、y坐标)
text(x = max(POI$Wavenumber_1080) * 0.8, 
     y = max(POI$Mass_Remaining) * 0.9, 
     labels = r_squared_text, 
     col = "black", 
     cex = 1.2)

关键说明:

  • 从模型摘要summary(model.1080)中提取r.squared字段获取决定系数
  • 用paste0()格式化显示文本,round()控制小数位数(这里保留3位)
  • text()函数的x和y参数可根据数据范围调整,确保文本位置合适

方法二:使用ggplot2绘图系统(更灵活美观)

如果习惯用ggplot2,结合annotate()或ggpubr包可以更便捷地添加R²:

基础ggplot2实现:

library(ggplot2)

ggplot(POI, aes(x = Wavenumber_1080, y = Mass_Remaining)) +
  geom_point(color = "red") +
  geom_smooth(method = "lm", color = "blue", se = FALSE) +  # 添加拟合线
  labs(title = "Summary of Regression Model 1080",
       x = "Intensities at Wavenumber 1080",
       y = "Mass Remaining") +
  annotate("text", 
           x = max(POI$Wavenumber_1080) * 0.8, 
           y = max(POI$Mass_Remaining) * 0.9, 
           label = paste0("R² = ", round(summary(model.1080)$r.squared, 3)),
           size = 4.5)

用ggpubr自动添加回归方程和R²:

library(ggpubr)

ggscatter(POI, x = "Wavenumber_1080", y = "Mass_Remaining",
          color = "red",
          add = "reg.line", conf.int = FALSE,
          xlab = "Intensities at Wavenumber 1080",
          ylab = "Mass Remaining",
          title = "Summary of Regression Model 1080") +
  stat_regline_equation(aes(label = ..r.label..))  # 仅显示R²,若要方程用..eq.label..

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 14:20:08