我可以输入自己的 ggplot 路径顺序吗?

Can I input my own order for a ggplot path?

在上面的图中,我使用散点图作为具有一系列节点的网络图。我想显示通过这些节点的多条路线。有没有一种方法可以输入节点列表作为路线,以便我可以按列表中的顺序将这些节点与同一地块上的多条路线连接起来? 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)

您可以使用因子水平来给定特定路线的节点:

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 package (v2.0.0)

于 2022-03-15 创建

我想你想使用 geom_path(),然后为备用路径定义一个具有所需顺序的新数据集:

library(ggplot2)

# make data
set.seed(1)
n <- 10
df <- data.frame(n = seq(n), x = runif(n), y = runif(n))

# re-order for alternate path
df2 <- df[sample(10),]

# plot
ggplot(data = df) + aes(x = x, y = y, label = n) + 
  geom_point() + 
  geom_text(nudge_y = 0.03) + 
  geom_path(arrow = arrow()) +
  geom_path(data = df2, arrow = arrow(), col = 2)

与用户 类似,但以编程方式更进一步,您还可以利用 ggplot 的列表特性,并为每个新路径创建一个列表。

路径根据您的评论。代码中的进一步评论

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 <- data.frame(x, y, number)

## list of paths
ways <- list(way1 = c(1, 5, 6, 2), way2 = c(1, 2, 8, 9))

## for a programmatic way of applying different colors - you can use any palette, really
mycols <- RColorBrewer::brewer.pal(length(ways), "Set1")
#> Warning in RColorBrewer::brewer.pal(length(ways), "Set1"): minimal value for n is 3, returning requested palette with 3 different levels

## For different colors, you need to loop by index 
my_paths <- lapply(seq_along(ways), function(i) {
  ## create new data sets for each path
  data <- df[df$number[ways[[i]]], ]
  ## create a new path for each data set
  geom_path(data = data, aes(x, y), color = mycols[i])
})

## add this list to your ggplot
ggplot(df, aes(x = x, y = y, label = number)) +
  geom_point(size = 5, shape = 19) +
  geom_text(vjust = -1) +
  my_paths

reprex package (v2.0.1)

于 2022-03-15 创建