循环遍历未命名的列以绘制 R 中的一张图

Looping through unnamed columns to plot on one graph in R

我有以下未命名列的数据框。

test_df <- structure(list(V1 = c(738, 734.55, 731.05, 727.48, 723.86, 720.18, 
716.45, 712.66, 708.82, 704.91), V2 = c(383, 379.31, 375.69, 
372.13, 368.64, 365.22, 361.87, 358.6, 355.37, 352.19), V3 = c(704, 
700.8, 697.52, 694.15, 690.71, 687.19, 683.59, 679.92, 676.12, 
672.21), V4 = c(316, 312.77, 309.66, 306.66, 303.8, 301.07, 298.49, 
296.07, 293.79, 291.63), V5 = c(746, 743.64, 741.15, 738.52, 
735.78, 732.93, 729.98, 726.92, 723.69, 720.31), V6 = c(369, 
364.63, 360.37, 356.21, 352.15, 348.21, 344.39, 340.68, 337.04, 
333.48), V7 = c(715, 711.38, 707.74, 704.06, 700.36, 696.63, 
692.87, 689.09, 685.31, 681.51), V8 = c(349, 345.79, 342.62, 
339.49, 336.39, 333.33, 330.3, 327.31, 324.26, 321.2)), .Names = c("V1", 
"V2", "V3", "V4", "V5", "V6", "V7", "V8"), row.names = c(NA, 
10L), class = "data.frame")

我希望在同一个图表上将每 2 列绘制在一起。我的数据输出是这样的,第一列是 "x" 变量,后面的列是 "y" 变量。 例如第1列,第2列是一个x,y坐标 和第3列,第4列是另一个x,y坐标。

我能够绘制第一列,但随后在尝试跨各种未命名列应用函数时遇到了困难。

plot(test_df$V1, test_df$V2, xlab="x", ylab ="y", xlim=c(200, 800), ylim=c(400, 200), main="vowel shapes", col= 'black', pch= ".")
lines(test_df$V1, test_df$V2, xlab="x", ylab ="y", xlim=c(200, 800), ylim=c(400, 200), main="vowel shapes", col= 'black', pch= ".")
lines(test_df$V3, test_df$V4, xlab="x", ylab ="y", xlim=c(200, 800), ylim=c(400, 200), main="vowel shapes", col= 'black', pch= ".")

我知道不建议循环,所以我觉得循环遍历列的长度很有趣。 谢谢!

matplot(test_df[seq(1,ncol(test_df), by=2)], test_df[seq(2,ncol(test_df), by=2)], t="l", lty=1)

使用 ggplot:

library(ggplot2)
df <- do.call(rbind, lapply(seq(1,ncol(test_df), by=2), 
      function(x) data.frame(x=test_df[,x], y=test_df[,x+1], plot=as.factor((x+1)/2))))
ggplot(df, aes(x,y, group=plot, col=plot)) + geom_line(lwd=1.5)