我正在使用包TSP探索R中的旅行推销员问题,一切正常,但是我唯一的问题是,图中未显示城市名称。

基本上在代码的最后一行,我想将行名作为标签

码:

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")

最佳答案

如果要在图表中使用城市名称作为标签,则可以在库ggplot中使用geom_text。诀窍是以正确的方式准备数据。

对于绘图,需要按路线对数据进行重新排序。

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


之后,您可以使用

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()


r - 在绘图中包括行名作为标签-LMLPHP

10-07 17:19