Repository navigation
Description
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
clauswilke commentedon Feb 3, 2019
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.
thomasp85 commentedon Feb 3, 2019
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...
thomasp85 commentedon Feb 3, 2019
An approach I would like would be some sort of method in the geom for acquiring specific scales - eg
self$get_scale("fill")paleolimbot commentedon Feb 4, 2019
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 thelayoutorpanel_params. I could work up a PR implementinglayout$get_scale("fill")because I think it would be minor...I would be happy to callGeom$get_scale()but I don't know how to make it happen.clauswilke commentedon Feb 4, 2019
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.
paleolimbot commentedon Feb 4, 2019
That's a great point...thanks to you both for considering this and let me know if there is anything I can do!
clauswilke commentedon Feb 4, 2019
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.
paleolimbot commentedon Feb 4, 2019
👍 will do!
paleolimbot commentedon Feb 13, 2019
I tried a few things! I'm sure there are other ways to go about this...
plot/Layer/Geomstack "stateful" (i.e., instances contain backreferences to the parent object, and theLayeradditionally contains a reference to theLayout). This allowsLayer$get_scale(which, panel), orGeom$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-layerCreated on 2019-02-13 by the reprex package (v0.2.1)
Layoutobject 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 originalScalesList, 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 theGeomdoesn't know anything about the layer in the current code). A toy version of that is here: master...paleolimbot:smarter-layoutCreated on 2019-02-13 by the reprex package (v0.2.1)
clauswilke commentedon Feb 14, 2019
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.
thomasp85 commentedon Feb 14, 2019
A general rule for most ggproto objects is that they should be stateless factories, so I would prefer a setup that keeps this
paleolimbot commentedon Feb 14, 2019
Layer info could be included in the data (similar to how the data contains a
PANELcolumn, it could contain aLAYERcolumn). Then one could get a layer-specific scale using something likeLayout$get_scale("x", data$PANEL[1], data$LAYER[1])from theGeomdraw methods. Without making the whole stack stateful, I can't think of a way to getGeom$get_scale()to work.clauswilke commentedon Feb 14, 2019
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_paramsorcoord? It doesn't belong intodata.paleolimbot commentedon Feb 14, 2019
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 theLayoutwould just need to overrideGeom$draw_layer()rather thanGeom$draw_panel()orGeom$draw_group().There's probably some other ways to get the layer ID into the draw method...the
dataseems like the least breaking way to do that, but it could also be set as a property of theLayerorGeomat build time.thomasp85 commentedon Feb 14, 2019
“Just” overwriting
draw_layeris 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 method40 remaining items
yutannihilation commentedon Feb 22, 2019
yutannihilation commentedon Feb 22, 2019
clauswilke commentedon Feb 22, 2019
yutannihilation commentedon Feb 22, 2019
clauswilke commentedon Feb 22, 2019
I created a separate issue for the
LayerSf()problem discussed in the hidden comments. Let's move any further discussion of that topic there: #3158clauswilke commentedon Feb 28, 2019
@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
paleolimbot commentedon Feb 28, 2019
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)!
clauswilke commentedon Feb 28, 2019
Good luck for your comps!
teunbrand commentedon Feb 17, 2025
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.thomasp85 commentedon Feb 25, 2025
Closing this as it seems stale. We can reopen if anyone feels strongly about it