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

ggplot折线图:如何在X轴按分组展示模型RMSE数据

解决RMSE折线图绘制问题

核心思路

要实现你想要的效果,关键是给每个模型的3个重复数据添加重复编号列(1/2/3),以此作为X轴变量,同时按Model分组来绘制折线。以下是具体步骤:

1. 预处理数据

首先为每个模型的3条记录添加重复编号:

library(ggplot2)

# 原始数据
data <- data.frame(
  RMSE = c(9.77, 9.6, 9.42, 7.98, 7.78, 7.63, 7.66, 7.65, 7.61, 6.63, 6.58, 6.43),
  Model = c("LR - LHS", "LR - LHS", "LR - LHS", "XGB - Reg", "XGB - Reg", "XGB - Reg",
            "RF - LHS", "RF - LHS", "RF - LHS", "XGB - LHS", "XGB - LHS", "XGB - LHS")
)

# 添加重复编号列(每个模型对应3个重复)
data$Replicate <- rep(1:3, 4)

2. 绘制目标折线图

使用ggplot2,按Model分组绘制折线,X轴显示重复编号并自定义标签,同时保留模型分组的区分:

ggplot(data, aes(x = Replicate, y = RMSE, group = Model, color = Model)) +
  # 绘制折线和数据点
  geom_line(linewidth = 1) +
  geom_point(size = 3) +
  # 自定义X轴标签为"模型1/2/3"
  scale_x_continuous(breaks = 1:3, labels = c("模型1", "模型2", "模型3")) +
  # 设置坐标轴和图例标题
  labs(x = "重复次数", y = "RMSE", color = "模型分组") +
  # 优化主题样式
  theme_minimal() +
  theme(
    axis.title.x = element_text(margin = margin(t = 15)),
    legend.position = "bottom",
    plot.margin = margin(b = 30)
  ) +
  # 可选:在X轴下方添加模型分组标注(对应手绘图样式)
  annotate("text", x = 2, y = min(data$RMSE) - 0.4, label = "LR - LHS", color = "#F8766D") +
  annotate("text", x = 2, y = min(data$RMSE) - 0.8, label = "XGB - Reg", color = "#00BA38") +
  annotate("text", x = 2, y = min(data$RMSE) - 1.2, label = "RF - LHS", color = "#619CFF") +
  annotate("text", x = 2, y = min(data$RMSE) - 1.6, label = "XGB - LHS", color = "#C77CFF")

为什么之前的尝试失败?

  • 若直接用Model作为X轴,会生成4个独立X值,每个模型的3个点会堆叠而非横向排列。
  • 若未设置group = Model,ggplot2无法识别哪些点属于同一模型,导致折线无法正确连接或生成混乱的线条。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 16:20:11