Skip to content

Feature request: allow access to the trained scales from the layout object #3116

Closed as not planned

Description

@paleolimbot

This is a fairly easy (I think) feature to add that would help me implement lazy reading of huge raster files (a stars proxy object), such that they can be downsampled appropriately. To do this, I would need access to the trained scales (for the fill and alpha aesthetics at draw time. Right now there is no way to access the trained scales except limited information about them in the panel_params and coordinates objects. I think that a reference to the ScalesList object could be included as an element of the layout object without any consequences? The Geom has access to the layout at draw time.

It is a completely valid point that this would be pushing ggplot2 where it perhaps should not go, coercing it to do things that it was not meant to do. I would argue that it is necessary if spatial rasters are ever going to be plotted in ggplot by those of us who don't have an intimate knowledge of downsampling (and maybe they shouldn't be). There is a brief discussion on the implementation of this at paleolimbot/ggspatial#17 . A reprex is included below.

library(ggplot2)
library(grid)

# in real life, this would be a reference to a large (scary) raster file
big_scary_raster <- tibble::tibble(raster = list(matrix(1:9, nrow = 3)))
StatMatrixList <- ggproto(
  "StatMatrixList",
  Stat,

  required_aes = "raster",
  default_aes = ggplot2::aes(fill = stat(z)),

  compute_layer = function(self, data, params, layout) {
    data$raster <- lapply(data$raster, function(x) {
      df <- reshape2::melt(x)
      names(df) <- c("x", "y", "z")
      df
    })

    tidyr::unnest(data, .data$raster)
  }
)

ggplot(big_scary_raster, aes(raster = raster)) +
  geom_raster(stat = StatMatrixList, hjust = 0, vjust = 0)

StatLazyMatrixList <- ggproto(
  "StatLazyMatrixList",
  StatMatrixList,

  compute_layer = function(self, data, params, layout) {
    # only return limits in the stat (these are usually cached in the raster file,
    # so the raster doesn't need to be loaded). Scales get trained based on the
    # result of this function.
    data$limits <- lapply(data$raster, function(raster) {
      tibble::tibble(
        x = c(0, ncol(raster)),
        y = c(0, nrow(raster)),
        z = range(raster)
      )
    })

    tidyr::unnest(data, .data$limits, .drop = FALSE)
  }
)

GeomLazyRaster <- ggproto(
  "GeomLazyRaster",
  Geom,
  required_aesthetics = "raster",

  default_aes = ggplot2::aes(alpha = "__default_alpha__", fill = "__default_fill__"),

  handle_na = function(data, params) {
    data
  },

  draw_panel = function(data, panel_params, coordinates) {
    # this is a super crazy hack
    # but there is no other way to get scale objects from the draw function at build time (?)
    scales <- NULL
    for(i in 1:20) {
      env <- parent.frame(i)
      if("plot" %in% names(env) && "scales" %in% names(env$plot) && inherits(env$plot$scales, "ScalesList")) {
        scales <- env$plot$scales
        break
      }
    }
    if(is.null(scales)) stop("@paleolimbot's hack to get the ScalesList from Geom$draw_panel() has failed :'(")
    fill_scale <- scales$get_scales("fill")
    alpha_scale <- scales$get_scales("alpha")

    if(all(data$alpha == "__default_alpha__")) {
      # default
      alpha <- function(x) 1
    } else if(length(unique(data$alpha)) == 1) {
      # set (or mapped but constant)
      alpha <- function(x) unique(data$alpha)
    } else if(!is.null(alpha_scale)) {
      # mapped
      alpha <- alpha_scale$map
    } else {
      stop("Don't know how to compute 'alpha'")
    }

    if(all(data$fill == "__default_fill__")) {
      # default
      fill <- function(x) 1
    } else if(length(unique(data$fill)) == 1) {
      # set (or mapped but constant)
      fill <- function(x) unique(data$fill)
    } else if(!is.null(fill_scale)) {
      # mapped
      fill <- fill_scale$map
    } else {
      stop("Don't know how to compute 'fill'")
    }

    gTree(
      raster = data$raster[[1]],
      fill = fill,
      alpha = alpha,
      coordinates = coordinates,
      panel_params = panel_params,
      cl = "lazy_raster_grob"
    )
  }
)


geom_lazy_raster <- function(mapping = NULL, data = NULL, stat = StatLazyMatrixList,
                             ..., inherit.aes = TRUE, show.legend = NA) {
  layer(
    geom = GeomLazyRaster,
    stat = stat,
    data = data,
    mapping = mapping,
    position = "identity",
    params = list(...),
    inherit.aes = inherit.aes,
    show.legend = show.legend
  )
}

makeContext.lazy_raster_grob <- function(x) {
  # here it's possible to determine height and width in inches
  # getting DPI from the graphics device may not be possible,
  # but can always fall back on a user-specified minimum

  # projection + resampling would happen here

  # apply the aesthetics
  colors <- x$fill(x$raster)
  alpha <- x$alpha(x$raster)
  colors <- paste0(colors, as.character.hexmode(scales::rescale(alpha, from = c(0, 1), to = c(0, 255))))
  dim(colors) <- dim(x$raster)

  # map the coordinates
  corners <- data.frame(x = c(0, ncol(x$raster)), y = c(0, nrow(x$raster)))
  corners_trans <- x$coordinates$transform(corners, x$panel_params)
  x_rng <- range(corners_trans$x, na.rm = TRUE)
  y_rng <- range(corners_trans$y, na.rm = TRUE)

  setChildren(x, gList(rasterGrob(
    # there is an axis irregularity between what we think of as rows
    # and what grid thinks of as rows
    aperm(colors, c(2, 1))[nrow(colors):1,],
    x = x_rng[1], y = y_rng[1],
    height = diff(y_rng), width = diff(x_rng),
    default.units = "native",
    interpolate = FALSE,
    hjust = 0,
    vjust = 0
  )))
}

ggplot(big_scary_raster, aes(raster = raster)) +
  geom_lazy_raster()

Created on 2019-02-03 by the reprex package (v0.2.1)

Activity

  1. clauswilke commented on Feb 3, 2019

    @clauswilke
    Member

    I think this feature would also help with generating filled contours at draw time from the new binning scale @thomasp85 is implementing. See #3044 and #3096.

  2. thomasp85 commented on Feb 3, 2019

    @thomasp85
    Member

    There are definitely enough meaningful examples to make us consider how to support it. I don’t personally think we should make the ScalesList object available as it is not currently an exported class we have committed to keeping stable. Making it available directly would limit our possibilities in the future all for the sake of a few (albeit important) needs...

  3. thomasp85 commented on Feb 3, 2019

    @thomasp85
    Member

    An approach I would like would be some sort of method in the geom for acquiring specific scales - eg self$get_scale("fill")

  4. paleolimbot commented on Feb 4, 2019

    @paleolimbot
    MemberAuthor

    How about as a method of the layout (i.e. layout$get_scale("fill"))? I don't think the geoms ever carry any stateful info, state is passed through in the layout or panel_params. I could work up a PR implementing layout$get_scale("fill") because I think it would be minor...I would be happy to call Geom$get_scale() but I don't know how to make it happen.

  5. clauswilke commented on Feb 4, 2019

    @clauswilke
    Member

    I think whatever solution we come up with requires careful thought so we don't box ourselves in for future development. We've talked a lot about layer-specific scales (e.g., different color scales for different layers), and if at all possible the approach taken now should be future-proof for that. (Even if we don't really know yet how to set up layer-specific scales.)

    This reasoning would suggest that it would be best if the scales could be made available through the Layer object, or directly through the Geom. I'm not immediately sure how to do this, but I think pondering a little longer is the right strategy.

  6. paleolimbot commented on Feb 4, 2019

    @paleolimbot
    MemberAuthor

    That's a great point...thanks to you both for considering this and let me know if there is anything I can do!

  7. clauswilke commented on Feb 4, 2019

    @clauswilke
    Member

    If you want to dig around some more in the ggplot2 code to develop potential strategies of how we can get scales info into the geom that would be helpful. Ideally, before we start coding, we'd have a list of potential approaches, each with pros and cons, and then we can make an informed decision about how to proceed.

  8. paleolimbot commented on Feb 4, 2019

    @paleolimbot
    MemberAuthor

    👍 will do!

  9. paleolimbot commented on Feb 13, 2019

    @paleolimbot
    MemberAuthor

    I tried a few things! I'm sure there are other ways to go about this...

    • Make the plot/Layer/Geom stack "stateful" (i.e., instances contain backreferences to the parent object, and the Layer additionally contains a reference to the Layout). This allows Layer$get_scale(which, panel), or Geom$layer$get_scale(which, panel). Of course, this opens up a lot of the internals to possible abuse by subclasses because they would have access to the whole object through the backreferences. I've implemented a toy version of this here: master...paleolimbot:stateful-layer
    library(ggplot2)
    
    GeomScaleInfo <- ggproto(
      "GeomScaleInfo", Geom,
      required_aes = "x",
      draw_panel = function(self, data, panel_params, coord) {
        
        x_scale <- self$layer$get_scale("x", 1L)
        col_scale <- self$layer$get_scale("colour")
        
        x_range <- x_scale$range$range
        col_limits <- col_scale$range$range
        
        if(is.null(x_range)) {
          text <- "NULL x-range"
        } else {
          text <- sprintf(
            "X-scale: %s-%s\ncol-scale: %s items", 
            x_range[1], x_range[2], length(col_limits)
          )
        }
        
        grid::textGrob(text, x = 1, y = 1, hjust = 1.1, vjust = 1.5)
      }
    )
    
    geom_scale_info <- function() {
      layer(
        geom = GeomScaleInfo, stat = "identity", data = data.frame(x = 1), mapping = aes(x = x), 
        position = "identity",
        params = list(), inherit.aes = FALSE, show.legend = NA
      )
    }
    
    ggplot(mpg, aes(displ, hwy, col = class)) + geom_point() + geom_scale_info()

    Created on 2019-02-13 by the reprex package (v0.2.1)

    • Make the Layout object have access to the non-position scales, in addition to the position scales (currently it contains the only valid reference to the trained position scales, but the non-position scales are in the original ScalesList, which also contains some confusing references to the untrained original position scales). This is more in the spirit of the current implementation, but definitely precludes anything that requires a reference to the layer (because even the Geom doesn't know anything about the layer in the current code). A toy version of that is here: master...paleolimbot:smarter-layout
    library(ggplot2)
    
    GeomScaleInfo <- ggproto(
      "GeomScaleInfo", Geom,
      required_aes = "x",
      
      # this approach requires overriding draw_layer() to pass on the layout object
      draw_layer = function(self, data, params, layout, coord) {
        if (ggplot2:::empty(data)) {
          n <- if (is.factor(data$PANEL)) nlevels(data$PANEL) else 1L
          return(rep(list(zeroGrob()), n))
        }
        
        # Trim off extra parameters
        params <- params[intersect(names(params), self$parameters())]
        
        args <- c(list(quote(data), quote(panel_params), quote(coord), quote(layout)), params)
        lapply(split(data, data$PANEL), function(data) {
          if (empty(data)) return(zeroGrob())
          
          panel_params <- layout$panel_params[[data$PANEL[1]]]
          do.call(self$draw_panel, args)
        })
      },
      
      draw_panel = function(self, data, panel_params, coord, layout) {
        
        x_scale <- layout$get_scale("x", 1L)
        col_scale <- layout$get_scale("colour")
        
        x_range <- x_scale$range$range
        col_limits <- col_scale$range$range
        
        if(is.null(x_range)) {
          text <- "NULL x-range"
        } else {
          text <- sprintf(
            "X-scale: %s-%s\ncol-scale: %s items", 
            x_range[1], x_range[2], length(col_limits)
          )
        }
        
        grid::textGrob(text, x = 1, y = 1, hjust = 1.1, vjust = 1.5)
      }
    )
    
    geom_scale_info <- function() {
      layer(
        geom = GeomScaleInfo, stat = "identity", data = data.frame(x = 1), mapping = aes(x = x), 
        position = "identity",
        params = list(), inherit.aes = FALSE, show.legend = NA
      )
    }
    
    ggplot(mpg, aes(displ, hwy, col = class)) + geom_point() + geom_scale_info()

    Created on 2019-02-13 by the reprex package (v0.2.1)

  10. clauswilke commented on Feb 14, 2019

    @clauswilke
    Member

    The first option seems nicer and more general to me. Not sure if there are any major downsides we're overlooking, though. Usually, a main design principle of software engineering is to avoid circular dependencies, and it seems this introduces one, since layer knows of geom and geom will know of layer after the change.

  11. thomasp85 commented on Feb 14, 2019

    @thomasp85
    Member

    A general rule for most ggproto objects is that they should be stateless factories, so I would prefer a setup that keeps this

  12. paleolimbot commented on Feb 14, 2019

    @paleolimbot
    MemberAuthor

    Layer info could be included in the data (similar to how the data contains a PANEL column, it could contain a LAYER column). Then one could get a layer-specific scale using something like Layout$get_scale("x", data$PANEL[1], data$LAYER[1]) from the Geom draw methods. Without making the whole stack stateful, I can't think of a way to get Geom$get_scale() to work.

  13. clauswilke commented on Feb 14, 2019

    @clauswilke
    Member

    There's an additional complication: if we change the arguments of draw_layer() etc. then all the third-party geoms that have been released will break.

    Is it possible to attach this information to either panel_params or coord? It doesn't belong into data.

  14. paleolimbot commented on Feb 14, 2019

    @paleolimbot
    MemberAuthor

    I don't think the arguments would need to be changed to implement Layout$get_scale("x", data$PANEL[1], data$LAYER[1])...the rare geometries that need to access the Layout would just need to override Geom$draw_layer() rather than Geom$draw_panel() or Geom$draw_group().

    There's probably some other ways to get the layer ID into the draw method...the data seems like the least breaking way to do that, but it could also be set as a property of the Layer or Geom at build time.

  15. thomasp85 commented on Feb 14, 2019

    @thomasp85
    Member

    “Just” overwriting draw_layer is not that simple as it needs to correctly split up and assemble everything efficiently. Pretty sure we could do this by adding a getter function to the param object we pass into the draw method

  16. 40 remaining items

  17. yutannihilation commented on Feb 22, 2019

    @yutannihilation
  18. yutannihilation commented on Feb 22, 2019

    @yutannihilation
  19. clauswilke commented on Feb 22, 2019

    @clauswilke
  20. yutannihilation commented on Feb 22, 2019

    @yutannihilation
  21. clauswilke commented on Feb 22, 2019

    @clauswilke
    Member

    I created a separate issue for the LayerSf() problem discussed in the hidden comments. Let's move any further discussion of that topic there: #3158

  22. clauswilke commented on Feb 28, 2019

    @clauswilke
    Member

    @paleolimbot Does the latest version of your code solve the problem you set out to solve? If yes, then I think you should open a PR and then we can resolve any remaining issues.

    Note that the PR will require a news item, as described here: https://style.tidyverse.org/news.html#bullets

  23. paleolimbot commented on Feb 28, 2019

    @paleolimbot
    MemberAuthor

    Sorry, I lost track of the thread and had to Ph.D. for a few days. Yes, the latest version of my code solves the problem, although I haven't unit tested yet. I will add some tests and the news item and PR after I defend my comps (today)!

  24. clauswilke commented on Feb 28, 2019

    @clauswilke
    Member

    Good luck for your comps!

  25. added
    feature
    and removed on May 22, 2019
  26. teunbrand commented on Feb 17, 2025

    @teunbrand
    Collaborator

    The example in #3116 (comment) works because geom_point() is training the scale, and it is just a 'reporter' geom instead of one that also needs to train/map/use the scale. The mechanism by which a scale should be trained is not very clear to me. If the data which requires delayed mapping has e.g. range 0-10, but a different layer has range 20-30 for the same aesthetic, then the scale will be trained as 20-30 and will not result in a good delayed mapping. If the scale is trained on the spot to have 0-30 range, then the second layer will be mismapped.

  27. thomasp85 commented on Feb 25, 2025

    @thomasp85
    Member

    Closing this as it seems stale. We can reopen if anyone feels strongly about it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureinternals 🔎

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions