sta*_*oob 5 r data-visualization igraph ggplot2
我正在使用 R 编程语言。
我在 R 中生成了以下随机数据集,并绘制了这些点的图:
library(ggplot2)
set.seed(123)
x_cor = rnorm(5,100,100)
y_cor = rnorm(5,100,100)
my_data = data.frame(x_cor,y_cor)
x_cor y_cor
1 43.95244 271.50650
2 76.98225 146.09162
3 255.87083 -26.50612
4 107.05084 31.31471
5 112.92877 55.43380
ggplot(my_data, aes(x=x_cor, y=y_cor)) + geom_point() + ggtitle("Travelling Salesman Example")
Run Code Online (Sandbox Code Playgroud)
假设我想按以下顺序将这些点连接在一起:1 与 3、3 与 4、4 与 5、5 与 2、2 与 1
我可以创建一个包含以下顺序的新变量:
my_data$order = c(3, 1, 4, 5, 2)
Run Code Online (Sandbox Code Playgroud)
使用ggplot2可以制作这种图吗?
我尝试了以下代码 - 但这是根据点出现的顺序而不是自定义顺序连接点:
ggplot(my_data, aes(x = x_cor, y = y_cor)) +
geom_path() +
geom_point(size = 2)
Run Code Online (Sandbox Code Playgroud)
我可能可以手动重新调整数据集以匹配此顺序 - 但有没有更简单的方法来做到这一点?
过去,我使用“igraph”制作了此类图表 - 但是否可以使用 ggplot2 制作它们?有人可以告诉我该怎么做吗?
谢谢!
您可以像这样订购数据:
my_data$order = c(1, 5, 2, 3, 4)
ggplot(my_data[order(my_data$order),], aes(x = x_cor, y = y_cor)) +
geom_path() +
geom_point(size = 2)
Run Code Online (Sandbox Code Playgroud)
如果要关闭路径,请使用geom_polygon:
ggplot(my_data[order(my_data$order),], aes(x = x_cor, y = y_cor)) +
geom_polygon(fill = NA, color = "black") +
geom_point(size = 2)
Run Code Online (Sandbox Code Playgroud)