我正在使用包探索 R 中的旅行商问题TSP,一切正常,但我唯一的问题是情节中城市的名称没有出现。
基本上在最后一行代码中,我想将行名作为标签
代码:
library(TSP)
set.seed(123)
x <- data.frame(x = runif(20), y = runif(20), row.names = LETTERS[1:20])
## create a TSP
etsp <- ETSP(x)
etsp
## use some methods
n_of_cities(etsp)
labels(etsp)
## plot ETSP and solution
tour <- solve_TSP(etsp)
tour
plot(etsp, tour, tour_col = "red")
Run Code Online (Sandbox Code Playgroud)
如果您想将城市名称作为图表中的标签,您可以geom_text在库 ggplot 中使用。诀窍是以正确的方式准备数据。
对于绘图,数据需要按路线重新排序。
tdf <- as.data.frame(tour)
orderd.cities.tf <- as.data.frame(etsp[tdf$tour,])
# x y
# C 0.40897692 0.64050681
# L 0.45333416 0.90229905
# A 0.28757752 0.88953932
Run Code Online (Sandbox Code Playgroud)
之后,您可以使用绘制此数据
ggplot(ordered.cities.tf,
aes(x=x,y=y,label=rownames(ordered.cities.tf)))+
geom_polygon(fill=NA,color="red")+
geom_point(shape=15,color="white",size=6)+geom_text()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6455 次 |
| 最近记录: |