Rui
Rui

Reputation: 317

How to connect several points from a fix point - R

I would like to connect a paired data always from a fix point (P2 in the data below). I have tried to use ggplot, but it appears to many lines. From the following data example:

A <-c(rep("A",4))
B <-c(rep("B",5))
X1<-c(-1,5,3,6)
X2<-c(5,0,2,9,3)
Y1<-c(1,-5,0,4)
Y2<-c(-6,0,1,9,-4)

df <- data.frame (Field = c(A,B),
      Point = c("P1","P2","P3","P4","P1","P2","P3","P4","P5"),
      X= c(X1,X2),
      Y= c(Y1,Y2))

I would like to obtain the following plot as exemplified for Field A (keeping point P2 as the staring value)

output <- data.frame ( Link =c("AP2-AP1","AP2-AP1","AP2-AP3","AP2-AP3","AP2-AP4","AP2-AP4"),
      X=c(5,-1,5,3,5,6),
      Y=c(-5,1,-5,0,-5,4))

Pretended plot:

library(ggplot2)
ggplot(output,aes(x=X, y=Y, group=Link)) +
geom_line()+ geom_point()+
theme_bw(base_size = 20)  

Upvotes: 3

Views: 360

Answers (1)

Henrik
Henrik

Reputation: 67818

You may use geom_segment. Then you need a data set with starting points (x, y) and end points (xend, yend) on each line.

This can be acheived by joining data with the "P2" points, with data without the "P2" points, within each "Field" (df[Point == "P2"][df[Point != "P2"], on = "Field"]). Here I use the data.table package for the join, but it can be done in several different ways.

library(data.table)
setDT(df)
ggplot(data = df, aes(X, Y, color = Field)) +
  geom_point() +
  geom_segment(data = df[Point == "P2"][df[Point != "P2"], on = "Field"],
               aes(xend = i.X, yend = i.Y))

enter image description here

P.S. I added color = Field just to make it easier to distinguish the two groups in this example.

Upvotes: 4

Related Questions