2016-11-15 75 views
2

我有以下未命名列的數據框。在無名列中循環繪製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") 

我正在尋找在同一個圖上繪製每兩列。我的數據輸出是這樣的,第一列是「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= ".") 

我知道不建議循環,所以我覺得有趣的循環遍歷列的長度。 謝謝!

回答

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

有同樣的想法,但你打我給它。我使用了'matplot(test_df [c(TRUE,FALSE)],test_df [c(FALSE,TRUE)],type =「l」,lty = 1)' – thelatemail

+0

這真是太神奇了,而且都很快。在這種特殊情況下,matplot是否允許改變圖的極限?我實際上是在尋找y軸從400到200,換句話說,從原點降序。情節基本上需要顛倒。 – RCN

+0

我的錯誤,發現它。非常感謝! – RCN

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) 

enter image description here