-1

I would like to connect the data points from highlight2 to their corresponding highlight3 data points

ggplot() + theme_classic() +
scale_x_continuous(limits = c(0,5), breaks = c(seq(0,5,1))) +
scale_y_continuous(limits = c(-50,100), breaks = c(seq(-50,100,50))) +
geom_point(data=highlight2,aes(x=A,y=B),color='red', size=4) +
geom_point(data=highlight3,aes(x=A,y=B),color='blue', size=4) +
theme(axis.text = element_text(size = 16, face="bold"))

Here is the plot so far. I basically want to connect the red dots to their corresponding blue dots on the plot.

enter image description here

Mohamed Momin
  • 25
  • 1
  • 5
  • 1
    Please include your data in the question: Have a look at https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example? in particular the sections: "Producing a minimal dataset" and "Copy your data". ideally provide your data in the form df <- data.frame(...) where "..." are your variables and values. – Peter May 20 '20 at 12:10

1 Answers1

2

You haven't included your data, so I've had to make some up. Essentially, you need to use geom_segment to join the points, which means you need to combine your two data frames into one. You can use dplyr to do this. Note that your call to ggplot is just the same as the one in your question except I have added in the geom_segment line.

library(dplyr)
library(ggplot2)

# Dummy data
set.seed(68)
highlight2 <- data.frame(A = runif(9, 0, 4), B = rnorm(9, 20, 30))
highlight3 <- data.frame(A = runif(9, 0, 4), B = rnorm(9, 20, 30))

# OP's plot
ggplot() + theme_classic() +
scale_x_continuous(limits = c(0,5), breaks = c(seq(0,5,1))) +
scale_y_continuous(limits = c(-50,100), breaks = c(seq(-50,100,50))) +
geom_point(data=highlight2,aes(x=A,y=B),color='red', size=4) +
geom_point(data=highlight3,aes(x=A,y=B),color='blue', size=4) +
theme(axis.text = element_text(size = 16, face="bold")) + 
# New bit
geom_segment(data = highlight2 %>% 
                    mutate(x2 = highlight3$A, y2 = highlight3$B),
             aes(x = A, y = B, xend = x2, yend = y2))

Created on 2020-05-20 by the reprex package (v0.3.0)

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87