I have two dfs
df1 <- data.frame(x= seq(1,1000,1), y=rnorm(1000,500,250), z=rep(1:4,250))
df2 <- data.frame(x = c(450,481,512,571), y=c(450,481,512,571), z=1:4)
I plot them as such;
library(ggplot2)
ggplot(df1)
geom_point(aes(x=x,y=y,color = z),alpha=0.2)
geom_point(data = df2, aes(x=x,y=y,color = z),size=4)
I would like that all x,y corresponding to say z=1 in df1, be connected to the x,y corresponding to z=1 in df2. This would create some sort of radiating lines from the points in df2. How can I accomplish this?
Thanks in advance.
CodePudding user response:
I would do a left join on the two data frames by z
, then use geom_segment
. It may make more sense to have z
coloured as a discrete variable too:
df3 <- dplyr::left_join(df1, df2, by = "z", suffix = c("_1", "_2"))
ggplot(df3)
geom_point(aes(x_1, y_1, color = factor(z)), alpha = 0.2)
geom_segment(aes(x_1, y_1, xend = x_2, yend = y_2, color = factor(z)),
alpha = 0.2)
geom_point(data = df2, aes(x, y, fill = factor(z)), size = 5,
color = "black", shape = 21)
theme_minimal()