ggforce icon indicating copy to clipboard operation
ggforce copied to clipboard

Reusing previously created geom_mark_hull() layer without recalculating?

Open razorofockham opened this issue 4 months ago • 2 comments

Thanks for the really nice package! I read in the documentation that "The hull is calculated at draw time, and can thus change as you resize the plot". I was wondering if there could be an easy way to reuse a previously calculated hull layer while overriding the recalculation, for instance when aiming at plotting the exact same hull over the same collection of points with an underlying layer that is changing. Below is a toy example of what I am trying to achieve. Here, plotDF would be a data frame with coordinates X/Y for points in a square grid, with each of these points having intensities Z for a set of different variables Var, and some (but not all) of these points in turn being univocally assigned to certain regions (specified by the column Region).

library(dplyr)
library(ggplot2)
library(ggforce)

hullDF <- plotDF[,c("X","Y","Region")] %>% filter(!is.na(Region)) %>% distinct()   # Unique X/Y/Region triplets
ggHull <- geom_mark_hull(data = hullDF, aes(x = X, y = Y, group = Region))         # Create hull layer before loop

for (V in unique(plotDF$Var)) {
    ggRasterAndHull <- ggplot(data = subset(plotDF, Var==V)) +
                       geom_raster(aes(x = X, y = Y, fill = Z)) +
                       ggHull    # Create raster for variable "V" overlaid with hull
    print(ggRasterAndHull )
}

The issue I find is that, as mentioned in the documentation, the hull layer gets recalculated at every iteration (I assume upon the call print()?), which in this case would not really be necessary, but takes the most time out of all the steps in the loop.

Thanks a lot for any guidance/hints you can provide!

razorofockham avatar Mar 02 '24 14:03 razorofockham