5

This question came up on answering How to show arrows in backward and forward directions in a ggplot2 legend?

I thought that a good way to automatically define the direction of the arrow in the glyph would be to pass this value, here "direction", as an aesthetic and to swap the direction of the segmentsGrob accordingly. It seems that draw_key_... uses "data" and "params" like Stat and Geom do, but it is only a data frame with a single row and it only contains four variables.

## browser()
# Browse[1]> data
# colour size linetype alpha
# 1 #F8766D  0.5        1    NA

I also tried - without success - to add direction as an aesthetic with:

GeomArrow <- ggproto(NULL, GeomSegment)
GeomArrow$required_aes <- c("x", "y", "xend", "yend", "direction")

How can I modify this data that is used in draw_key?

library(ggplot2)
foo <- structure(list(direction = c("backward", "forward"), 
                      x = c(0, 0), xend = c(1, 1), y = c(1, 1.2), 
                      yend = c(1, 1.2)), row.names = 1:2, class = "data.frame")

StatArrow <- ggproto(NULL, StatIdentity)
StatArrow$compute_layer <- function (self, data, params, layout) 
{
    swap <- data$direction == "backward"
    v1 <- data$x
    v2 <- data$xend
    data$x[swap] <- v2[swap]
    data$xend[swap] <- v1[swap]
    data
}

# draw_key_segment_custom <- function(data, params = list(direction), size) {
## ... 
## the idea was to simply switch x0 and x1 in the segmentsGrob depending on the new aesthetic
## This does not work because "data$direction" does not exist
## something like 
  # if(data$direction == "backward") {
  #   x0 = 0.9
  #   x1 = 0.1
  # } else {
  #   x0 = 0.1
  #   x1 = 0.9
  # }
  ## then 
  # grid::segmentsGrob(x0, 0.5, x1, 0.5,
                     ##...)
## but 
## browser()
# Browse[1]> data
# colour size linetype alpha
# 1 #F8766D  0.5        1    NA

# }

## direction as an aesthetic works despite this warning
ggplot() +
  geom_segment(data = foo,
               stat = "arrow",
               aes(x, y, xend = xend, yend = yend, col = direction, 
                   direction = direction),
               arrow = arrow(length = unit(0.3, "cm"), type = "closed")
             ## does not work, as per above
             # key_glyph = "segment_custom"
)
#> Warning: Ignoring unknown aesthetics: direction

Created on 2022-06-28 by the reprex package (v2.0.1)

tjebo
  • 21,977
  • 7
  • 58
  • 94
  • 3
    Yep. Would be nice to have that option. The option I use for this kind of manipulations is via the value of the available aesthetics. See e.g. [ggplot legend with the use of emojis](https://stackoverflow.com/questions/72448513/ggplot-legend-with-the-use-of-emojis/72449373#72449373) or [Add text to legend symbols in ggplot](https://stackoverflow.com/a/72660761/12993861) or [R rotate vline in ggplot legend with scale_linetype_manual](https://stackoverflow.com/questions/69064192/r-rotate-vline-in-ggplot-legend-with-scale-linetype-manual/69065721#69065721) – stefan Jun 28 '22 at 10:02
  • 2
    Yeah. Agreed. Would be nice to have a cleaner mechanism to do these manipulations. – stefan Jun 28 '22 at 11:03
  • would passing an additional argument to the draw_key function work? [small example](https://stackoverflow.com/questions/49965758/change-geom-texts-default-a-legend-to-label-string-itself/49966784#49966784) – user20650 Jun 29 '22 at 16:26
  • @user20650 I don't think this works. In your example you are passing external data as new arguments, and I'd like to access the aesthetics as defined in aes(). This must be possible somehow, but I have no clue where and when the draw_key function gets the aesthetics from – tjebo Jun 29 '22 at 16:38
  • 1
    @user20650 it's still a great workaround and I realised I had already given you an upvote for this probably a long time ago :D The principle is similar to Stefan's workaround – tjebo Jun 29 '22 at 16:40
  • And, in the context of polygons, this would be applicable to winding directions, perhaps? – Chris Jul 04 '22 at 03:27

1 Answers1

8

I think you first thought was correct, that it would be a required_aes of the Geom. If we make such a Geom:

library(ggplot2)
library(rlang)

foo <- structure(list(direction = c("backward", "forward"), 
                      x = c(0, 0), xend = c(1, 1), y = c(1, 1.2), 
                      yend = c(1, 1.2)), row.names = 1:2, class = "data.frame")

GeomArrow <- ggproto(
  NULL, GeomSegment,
  required_aes = c("x", "y", "xend", "yend", "direction"),
  draw_layer = function (self, data, params, layout, coord) 
  {
    swap <- data$direction == "backward"
    v1 <- data$x
    v2 <- data$xend
    data$x[swap] <- v2[swap]
    data$xend[swap] <- v1[swap]
    GeomSegment$draw_layer(data, params, layout, coord)
  }
)

And declare an appropriate key drawing function

draw_key_arrow = function(data, params, size) {
  grid::segmentsGrob(
    x0 = ifelse(data$direction == "forward", 0.1, 0.9),
    x1 = ifelse(data$direction == "forward", 0.9, 0.1),
    # Rest is just like vanilla
    y0 = 0.5, y1 = 0.5,
    gp = grid::gpar(
      col  = alpha(data$colour %||% data$fill %||% "black", data$alpha),
      fill = alpha(params$arrow.fill %||% data$colour %||% data$fill %||% 
                     "black", data$alpha),
      lwd = (data$size %||% 0.5) * .pt,
      lty = data$linetype %||% 1, lineend = "butt"
    ),
    arrow = params$arrow
  )
}

Then we should be able to render the plot if (!!!) we also map the direction aesthetic to a scale with a legend.

ggplot() +
  stat_identity(
    geom = GeomArrow,
    data = foo,
    aes(x, y, xend = xend, yend = yend, col = direction, direction = direction),
    arrow = arrow(length = unit(0.3, "cm"), type = "closed"),
    key_glyph = draw_key_arrow
  ) +
  # Hijacking a generic identity scale by specifying aesthetics
  scale_colour_identity(aesthetics = "direction", guide = "legend")

Created on 2022-07-04 by the reprex package (v2.0.1)


From comments: The relevant source code can be currently found in ggplot2/R/guide-legend.r

tjebo
  • 21,977
  • 7
  • 58
  • 94
teunbrand
  • 33,645
  • 4
  • 37
  • 63
  • Do you think this also works with other scale_ functions? – tjebo Jul 04 '22 at 11:17
  • 1
    There are various ways in which the `data` in the `draw_key_*()` ends up with columns. One is the `default_aes` of a layer, the other through mapped aesthetics. The default aes route doesn't work, because it would just return a static parameter that is useless for legend purposes. – teunbrand Jul 04 '22 at 11:22
  • Do you mean other scales than the identity scales or other scales as in other aesthetics? – teunbrand Jul 04 '22 at 11:22
  • other scales such as scale_color_brewer – tjebo Jul 04 '22 at 11:24
  • I mean yes, in theory, but I don't know what `direction = "#ABCDEF"` would mean and it likely gets misinterpreted in the `draw_key_*()`. – teunbrand Jul 04 '22 at 11:26
  • 2
    The relevant source code is [here](https://github.com/tidyverse/ggplot2/blob/50e917a230d7347a30e2ebcca1e3baa9a4b82072/R/guide-legend.r#L260-L284) but it seems quite complicated. – teunbrand Jul 04 '22 at 11:32
  • Is it possible to control the colours of the arrows using this approach? – VictimOfMaths Feb 13 '23 at 18:10