user111024
user111024

Reputation: 811

paired segments in ggplot

Given foo I'd like to connect pairs of points so that there is a line between foo[1,] and foo[11,], foo[2,] and foo[12,], up to foo[10,] and foo[20,]. Seems like this should be possible with an artful call to geom_segment and the grouping variable id?

foo <- data.frame(id = c(1:10,1:10),
                  samp = rep(c("A","B"),each=10),
                  x = c(rnorm(10,mean = 5),rnorm(10,mean = 5)),
                  y = c(rnorm(10,mean = 5),rnorm(10,mean = 6)))
ggplot(foo,aes(x=x,y=y,col=samp)) + geom_point()

Any help appreciated.

Upvotes: 2

Views: 114

Answers (1)

akrun
akrun

Reputation: 887128

We need to use the group as 'id' in the geom_line

library(ggplot2)
ggplot(foo) + 
    geom_point(aes(x = x,y = y, col = samp)) + 
    geom_line(aes(x = x, y = y, group = id))

-output enter image description here

Upvotes: 2

Related Questions