如何在 ggplot2 图例中显示向后和向前的箭头?

bir*_*ird 7 r ggplot2

我有一个dataframe带有箭头坐标的:

arrows = data.frame(direction = factor(c("forward", "backward", "backward")),
                x = c(0, 0, 0),
                xend = c(1, 1, 1),
                y = c(1, 1.2, 1.1),
                yend = c(1, 1.2, 1.1))
Run Code Online (Sandbox Code Playgroud)

我想使用这些数据来绘制箭头 - 有些是向前的,反之亦然。

到目前为止我尝试过:

library(ggplot2)

ggplot() +
        geom_segment(data = arrows, 
                     aes(x, y, xend = xend, yend = yend, col = direction),
                     arrow = arrow(length = unit(0.3, "cm"), type = "closed", ends = c("last", "first")))
Run Code Online (Sandbox Code Playgroud)

其产生:

在此输入图像描述

我想在这个图中解决两个问题:

  1. 我如何确保ggplot“理解”哪个情节是“向前”和“向后”,以便为他们提供正确的图例?

  2. 如何更改图例,使其显示前进方向,并带有向前的箭头和向后的向后箭头?

Jon*_*ing 7

也许有两个图例,其中一个使用自定义字形?

在此输入图像描述

draw_key_arrow_left <- function(data, params, size, dir) {
  if (is.null(data$linetype)) {
    data$linetype <- 0
  } else {
    data$linetype[is.na(data$linetype)] <- 0
  }
  
  segmentsGrob(0.9, 0.5, 0.1, 0.5,
               gp = gpar(
                 col = alpha(data$colour %||% data$fill %||% "black", data$alpha),
                 # the following line was added relative to the ggplot2 code
                 fill = alpha(data$colour %||% data$fill %||% "black", data$alpha),
                 lwd = (data$size %||% 0.5) * .pt,
                 lty = data$linetype %||% 1,
                 lineend = "butt"
               ),
               arrow = params$arrow
  )
}


arrows2 <- arrows %>%
  mutate(x_orig = x, xend_orig = xend,
         x = if_else(direction == "forward", x_orig, xend_orig),
         xend = if_else(direction == "forward", xend_orig, x_orig))

ggplot() +
  geom_segment(data = arrows2 %>% filter(direction == "forward"),
               aes(x, y, xend = xend, yend = yend, col = direction),
               arrow = arrow(length = unit(0.3, "cm"), type = "closed")) +
  scale_color_manual(values = "#F8766D") +
  
  ggnewscale::new_scale_color() +
  geom_segment(data = arrows2 %>% filter(direction == "backward"),
               aes(x, y, xend = xend, yend = yend, col = direction),
               arrow = arrow(length = unit(0.3, "cm"), type = "closed"),
               key_glyph = "arrow_left") +
  scale_color_manual(values = "#619CFF", name = "") +
  theme(legend.key.width=unit(0.7,"cm"))
Run Code Online (Sandbox Code Playgroud)