
在上面的圖中,我使用散點圖作為具有一系列節點的網路圖。我想通過這些節點顯示多條路線。有沒有辦法可以輸入節點串列作為路線,以便我可以按串列中的順序將這些節點與同一圖上的多條路線連接起來?geom_path() 僅按照節點在資料集中的順序連接它們,我可以輸入自己的順序嗎?
library(ggplot2)
number <- 1:10
x <- c(10,2,38,45,34,67,23,45,25,49)
y <- c(60,50,23,35,76,37,21,75,34,56)
df <- tibble(x,y,number)
ggplot(df,aes(x=x,y=y,label=number))
geom_point(size=5,shape=19) geom_text(vjust=-1)
uj5u.com熱心網友回復:
與 box 的解決方案中的用戶
uj5u.com熱心網友回復:
您可以使用因子級別對給定路線的節點進行排序:
library(tidyverse)
points <- tribble(
~id, ~x, ~y, ~type,
1, 1, 1, "Depot",
2, 1, 2, "Item",
3, 2, 1, "Item",
4, 2, 2, "Item"
)
routes <- list(
"route1" = c(4, 2, 1), # start with 4 and then move to 1 via 2
"route2" = c(4, 2, 3, 1),
"route3" = c(1, 3, 1, 4)
)
route_points <- function(route, name) {
points %>%
mutate(new_id = id %>% factor(levels = unique(route))) %>%
arrange(new_id) %>%
filter(!is.na(new_id)) %>%
mutate(route = name)
}
points %>%
ggplot(aes(x, y))
geom_path(data = route_points(routes[[1]], names(routes)[[1]]), mapping = aes(color = route))
geom_path(data = route_points(routes[[2]], names(routes)[[2]]), mapping = aes(color = route))
geom_path(data = route_points(routes[[3]], names(routes)[[3]]), mapping = aes(color = route))
geom_label(aes(label = id, color = type))

由reprex 包于 2022-03-15 創建 (v2.0.0 )
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/444189.html
