2014-10-28 159 views
0

我在R中使用ggplot2創建散點圖。我有兩個不同的情況(x,y)的數據集如下:散點圖與軌跡跨數據集

x1   y1   x2    y2 
1 1.00000000 150.36247 0.50000000 133.27397 
2 1.00000000 129.62707 0.50000000 120.79893 
3 1.00000000 79.94730 0.62500000 78.98120 
4 1.00000000 79.78723 0.62500000 81.93014 
5 1.00000000 133.47697 0.72727273 192.86557 

我想繪製在同一個圖(X1,Y1)和(x2,y2)和繪製軌跡線連接兩點,數據集中的每一行。例如,在上面的示例數據中,將會有一條連接(1,150)到(0.5,133)(來自行1的數據)和連接(1,129)和(0.5,120)的單獨行(來自行2)等。理想情況下,我也想讓每一行都有不同的顏色。

我試着按照下面的說明創建的軌跡,但在我的數據集的分組是按列而不是按行:Scatterplot with developmental trajectoriesMaking a trajectory plot using R

目前,我的腳本只是產生在同一圖中,兩個散點圖但有是同一行的數據點之間沒有連接:

scatter2<-ggplot(data = df, aes(x=x1, y=y1)) 
+ geom_point(aes(x=x1, y=y1), color="red") 
+ geom_point(aes(x=x2, y=y2), color="blue") 

任何幫助,您可以提供將不勝感激!謝謝!

回答

1

這可以通過使用geom_segment()來實現。你可以在這裏找到更多的信息:http://docs.ggplot2.org/current/geom_segment.html

我想在這裏,你會做這樣的事情

scatter2<-ggplot(data = df, aes(x=x1, y=y1)) 
    + geom_point(aes(x=x1, y=y1), color="red") 
    + geom_point(aes(x=x2, y=y2), color="blue") 
    + geom_segment(aes(x=x1, y=y1, xend=x2, yend=y2)) 
+0

謝謝!作爲附加,我還添加了方向性和顏色的箭頭:'geom_segment(aes(x = x1,y = y1,xend = x2,yend = y2,color = df $ dist),arrow = arrow角度= 25,長度=單位(0.25,「cm」)))+ scale_colour_gradientn(顏色=彩虹(4))'其中df $ dist是連接點的長度 – 2014-10-28 17:36:58

1
DF <- read.table(text=" x1   y1   x2    y2 
1 1.00000000 150.36247 0.50000000 133.27397 
2 1.00000000 129.62707 0.50000000 120.79893 
3 1.00000000 79.94730 0.62500000 78.98120 
4 1.00000000 79.78723 0.62500000 81.93014 
5 1.00000000 133.47697 0.72727273 192.86557", header=TRUE) 

整理你的數據:

DF$id <- seq_len(nrow(DF)) 
library(reshape2) 
DF <- melt(DF, id.var="id") 
DF$var <- substr(DF$variable, 1, 1) 
DF$group <- substr(DF$variable, 2, 2) 
DF$variable <- NULL 
DF <- dcast(DF, group + id ~ var) 

簡介:

library(ggplot2) 
ggplot(DF, aes(x=x, y=y)) + 
    geom_point(aes(shape=group), size=5) + 
    geom_line(aes(colour=factor(id))) 

resulting plot