I am trying to create a scatter plot that has paths between all points within a certain distance of each other using ggplot2, similar to the attached image below. How could I modify the following code to include paths between all points within a distance of 0.2 to each other?
library(ggplot)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point()
this duplicates line segment draws which is not very efficient but I think that's what you're looking for
df_iris <- data.frame(x = iris$Sepal.Length, y = iris$Sepal.Width)
df_graph = data.frame(x1 = rep(df_iris$x,nrow(df)),
y1 = rep(df_iris$y,nrow(df)),
x2 = rep(df_iris$x,1,each=nrow(df)),
y2 = rep(df_iris$y,1,each=nrow(df))
)
df_graph$dist = sqrt((df_graph$x2-df_graph$x1)^2+(df_graph$y2-df_graph$y1)^2)
threshold = 0.2
df_graph = df_graph[df_graph$dist>0&df_graph$dist<threshold,]
library(ggplot2)
ggplot(df_graph)+
geom_segment(aes(x=x1,y=y1,xend=x2,yend=y2),color="blue")+
geom_point(data=df_iris, aes(x=x,y=y),size=0.2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.