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

如何在R中计算数据集两组数据的RMSE并添加至散点图

为分组散点图添加RMSE标注的解决方案

核心思路

先按machine分组计算每组的RMSE,再将计算结果作为文本标注添加到已有的散点图中。

完整代码实现

# 加载所需包
library(dplyr)
library(ggplot2)
library(ggpmisc) # 用于stat_poly_eq函数

# 加载数据集(如果是本地csv文件,替换为fr <- read.csv(file.choose()))
fr <- structure(list(machine = c("B", "B", "B", "B", "B", "B", "B", 
"B", "B", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A"), 
    measured = c(14.47, 15.33, 18.56, 14.89, 17.24, 16.25, 13, 
    20.52, 18.06, 13.09, 16.88, 15.92, 14.47, 18.63, 13.88, 16.32, 
    13.83, 11.67, 13.42), predicted = c(15.83, 16, 17.87, 14.21, 
    17.77, 14.14, 12.01, 19.31, 16.98, 13.19, 15.6, 17.16, 16.07, 
    17.38, 17.99, 17.86, 18.54, 10.79, 16.06)), class = "data.frame", row.names = c(NA, 
-19L))

# 分组计算RMSE,并确定标注位置
rmse_data <- fr %>%
  group_by(machine) %>%
  summarise(
    rmse = sqrt(mean((measured - predicted)^2)), # RMSE计算公式
    x_pos = max(measured), # 标注的x坐标(每组实测值最大值)
    y_pos = min(predicted) # 标注的y坐标(每组预测值最小值)
  ) %>%
  mutate(label = paste0("RMSE = ", round(rmse, 2))) # 格式化标注文本

# 绘制散点图并添加RMSE标注
ggplot(fr, aes(measured, predicted, colour = machine)) +
  geom_point(size=2)+
  geom_smooth(method="lm", se=FALSE) +
  # 添加RMSE文本标注
  geom_text(data = rmse_data, aes(x = x_pos, y = y_pos, label = label), 
            hjust = 1, vjust = 0, show.legend = FALSE) +
  stat_poly_eq(aes(label = paste(after_stat(eq.label),
                                 after_stat(rr.label), sep = "*\", \"*"))) +
  theme_bw(base_size=16) +
  theme(axis.line = element_line(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank())

关键步骤说明

  1. RMSE计算:用dplyr分组后,通过sqrt(mean((measured - predicted)^2))计算标准RMSE,保留2位小数让标注更整洁。
  2. 标注位置设置:选择每组实测值的最大值和预测值的最小值作为标注坐标,确保标注在每组散点的边缘区域,不会遮挡数据点。
  3. 添加标注:通过geom_text调用预计算好的rmse_data,指定位置和文本内容,关闭图例避免干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 21:01:01