【发布时间】:2021-05-09 13:53:55
【问题描述】:
我正在尝试使用 ggplot2 创建一个散点图,该散点图在所有点之间具有一定距离内的路径,类似于下面的附图。如何修改以下代码以包含彼此距离为 0.2 的所有点之间的路径?
library(ggplot)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point()
【问题讨论】:
我正在尝试使用 ggplot2 创建一个散点图,该散点图在所有点之间具有一定距离内的路径,类似于下面的附图。如何修改以下代码以包含彼此距离为 0.2 的所有点之间的路径?
library(ggplot)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point()
【问题讨论】:
这重复了线段绘制,效率不高,但我认为这就是你要找的
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)
【讨论】: