2014-10-28 156 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