This function allows you to apply a custom filtering function to a layer. The
function must take a nativeRaster
object as the first argument along with
any other arguments passed to ...
. Be aware that the raster spans the full
device size and not just the viewport currently rendered to. This is because
graphics may extend outside of the viewport depending on the clipping
settings. You can use get_viewport_area()
along with all the other raster
helpers provided by ggfx to facilitate working with the input raster. See the
example below for some inspiration.
with_custom(x, filter, ...)
A ggplot2 layer object, a ggplot, a grob, or a character string naming a filter
A function taking a nativeRaster
object as the first argument
along with whatever you pass in to ...
Additional arguments to filter
Depending on the input, either a grob
, Layer
, list of Layer
s,
guide
, or element
object. Assume the output can be used in the same
context as the input.
library(ggplot2)
flip_raster <- function(raster, horizontal = TRUE) {
# Get the viewport area of the raster
vp <- get_viewport_area(raster)
# Get the columns and rows of the raster - reverse order depending on
# the value of horizontal
dims <- dim(vp)
rows <- seq_len(dims[1])
cols <- seq_len(dims[2])
if (horizontal) {
cols <- rev(cols)
} else {
rows <- rev(rows)
}
# change the order of columns or rows in the viewport raster
vp <- index_raster(vp, cols, rows)
# Assign the modified viewport back
set_viewport_area(raster, vp)
}
ggplot() +
with_custom(
geom_text(aes(0.5, 0.75, label = 'Flippediflop!'), size = 10),
filter = flip_raster,
horizontal = TRUE
)
ggplot() +
with_custom(
geom_text(aes(0.5, 0.75, label = 'Flippediflop!'), size = 10),
filter = flip_raster,
horizontal = FALSE
)