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

如何在R中逐行迭代绘制每行的成对Y值

每行成对Y值绘图实现方法

你的需求是把数据框每行的T0和T3两个数值绘制成带连接线的对比图,下面提供两种实用的R语言实现方式:

方法一:基础R绘图(逐行迭代实现)

直接通过循环逐行处理数据,手动绘制线段和点:

# 先准备数据
T0 <- c(1842,2047,1831,2627,1769)
T3 <- c(13842,6847,4480,15873,17163)
test <- data.frame(T0, T3)

# 初始化绘图区域,设置坐标轴范围和标签
plot(0, 0, type = "n", xlim = c(1, nrow(test)), ylim = range(test), 
     xlab = "行号", ylab = "数值", main = "每行T0与T3值对比")

# 逐行循环绘制
for (i in 1:nrow(test)) {
  # 画连接T0和T3的竖线
  lines(c(i, i), c(test$T0[i], test$T3[i]), col = "gray")
  # 标记T0的点
  points(i, test$T0[i], pch = 16, col = "blue")
  # 标记T3的点
  points(i, test$T3[i], pch = 17, col = "red")
}

# 添加图例区分两组数据
legend("topright", legend = c("T0", "T3"), pch = c(16,17), col = c("blue", "red"))

方法二:ggplot2绘图(无需循环,更简洁)

通过将宽格式数据转为长格式,利用ggplot的语法快速生成图形,代码更易维护:

library(ggplot2)
library(tidyr)

# 准备数据
T0 <- c(1842,2047,1831,2627,1769)
T3 <- c(13842,6847,4480,15873,17163)
test <- data.frame(T0, T3)

# 把宽格式数据转成适合ggplot的长格式
test_long <- pivot_longer(test, cols = c(T0, T3), names_to = "组别", values_to = "数值")
test_long$行号 <- rep(1:nrow(test), 2)

# 生成图形
ggplot(test_long, aes(x = 行号, y = 数值, color = 组别, shape = 组别)) +
  geom_line(aes(group = 行号), color = "gray") + # 每行的连接线
  geom_point(size = 3) +
  labs(x = "行号", y = "数值", title = "每行T0与T3值对比") +
  theme_bw()

两种方法都能生成你需要的效果:每行对应一组两个点,用灰色竖线连接,不同组的点用不同颜色和形状区分。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 01:57:20