Home > Back-end >  Can I input my own order for a ggplot path?
Can I input my own order for a ggplot path?

Time:03-16

My plot

In my plot above, I'm using a scatter plot as a network graph with a series of nodes. I am wanting to show multiple routes through these nodes. Is there a way I can input a list of nodes as a route so that I can connect those nodes in the order in the list with multiple routes on the same plot? geom_path() only connects them in the order the nodes are in in the dataset, can I input my own order?

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)

CodePudding user response:

Similar to user enter image description here

CodePudding user response:

You can use factor levels to order your nodes given a certain route:

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

Created on 2022-03-15 by the reprex package (v2.0.0)

  • Related