Search code examples
rggplot2vectorplotline

ggplot line segments from one point to many from different dataframes


I have one df with start points for 2 groups, and another with end points for those same groups. I want to make a ggplot drawing lines from the group 1 start to all group 1 ends that meet a condition, and from the group 2 starts to all group 2 ends that meet the condition, but I don't know what geom_ I need to use to make that happen, of if I can do it from two different dataframes as I'm attempting to.

 # start coordinates:
 set.seed(5)
 start <- data.frame(matrix(nrow=2,ncol=3))
 colnames(start) <- c("group","X","Y")
 start$group <- c(1,2)
 start$X <- c(5,10)
 start$Y <- c(5,10)

 # end coordinates:
 df <- data.frame(matrix(nrow = 20,ncol=4))
 colnames(df) <- c("group","X","Y","condition")
 df$group <- rep(c(1,2),each=10)
 df$X <- runif(20,0,20)
 df$Y <- runif(20,0,20)
 df$condition <- c("n","n","n","y","n",
                   "y","n","n","y","y",
                   "y","n","n","y","n",
                   "y","y","y","n","y")

 # plot data
 library(ggplot2)
 ggplot(data=df,aes(x=X,y=Y,color=group))+
      geom_point(aes(shape=condition))+
      geom_point(data=start,aes(x=X,y=Y),size=2)

What I want is lines all coming out from the start point to only the "condition=yes" end points for each group. The graph would kind of look like two overlapping stars, but I can't figure out how to call from two dataframes in one geom_ command. Here's what I tried so far.

 ggplot(data=df,aes(x=X,y=Y,color=group))+
 geom_point(aes(shape=condition))+
 geom_point(data=start,aes(x=X,y=Y),size=2)+  
 geom_segment(aes(x=start$X,
                  y=start$Y,
                  xend=df$X[df$condition=="y"],
                  yend=df$Y[df$condition=="y"],
                  group=group))

But this didn't work. Not sure if geom_segment is what I should be using anyway.


Solution

  • merged.data <- merge(x=start, y=df, by="group")
    colnames(merged.data) <- c("group", "X.start", "Y.start", "X.end", "Y.end", "condition")
    
    ggplot(df, aes(x=X, y=Y, color=as.character(group))) + 
      geom_point(size=2)  +
      geom_point(data=start, aes(x=X, y=Y, color=as.character(group)), size=2) +
      geom_segment(data=merged.data[merged.data$condition == "y", ], aes(x=X.start, y=Y.start, xend=X.end, yend=Y.end, color=as.character(group)))
    

    enter image description here