Intro Thoughts

Status Quo

library(tidyverse)

ggplot(cars) + 
  aes(speed, dist) + 
  geom_point(size = .15) ->
base; base

compute_mean <- function(data, scales){
  
  data %>% 
    summarise(x = mean(x),
              y = mean(y))
  
}

########  groupwise computation via compute group ####
StatMeangroup <- ggproto(`_class` = "StatMeangroup",
                         `_inherit` = Stat,
                         compute_group = compute_mean)



base +
  layer(geom = "point", 
        stat = StatMeangroup, 
        position = "identity") + 
  aes(color = speed > 15)

########  panel-wise computation by defining compute panel #####
StatMeanpanel <- ggproto(`_class` = "StatMeanpanel",
                         `_inherit` = Stat,
                         compute_panel = compute_mean)

base +
  layer(geom = "point", 
        stat = StatMeanpanel, 
        position = "identity") + 
  aes(color = speed > 15)

last_plot() +
  facet_wrap(facets = vars(speed > 15))

########  layer wise computation via compute_layer??? ####
StatMeanlayer <- ggproto(`_class` = "StatMeanlayer",
                         `_inherit` = Stat,
                         compute_layer = compute_mean)


# expect a point in each facet that computes the mean for the entire layer. 
base +
  layer(geom = "point", 
        stat = StatMeanlayer, 
        position = "identity") + 
  aes(color = speed > 15) +
  facet_wrap(facets = vars(speed > 15))
## Error:
## ! Problem while computing stat.
## ℹ Error occurred in the 2nd layer.
## Caused by error in `compute_layer()`:
## ! unused argument (<environment>)

Experiment

library(tidyverse)

compute_mean <- function(data, ...){
  
  data %>% 
    distinct(PANEL) ->
  panel_df
  
  data %>% 
    summarise(x = mean(x),
              y = mean(y)) %>% 
    crossing(panel_df)
      
  
}

########  groupwise computation via compute group ####
StatMeanlayer <- ggproto(`_class` = "StatMeanlayer",
                         `_inherit` = Stat,
                         compute_layer = compute_mean)

ggplot(cars) + 
  aes(speed, dist) + 
  geom_point(size = .15) +
  layer(geom = "point", 
        stat = StatMeanlayer, 
        position = "identity")

last_plot() +
  facet_wrap(facets = vars(speed > 10)) 

layer_data(i = 2)
## # A tibble: 2 × 9
##       x     y PANEL shape colour  size fill  alpha stroke
##   <dbl> <dbl> <fct> <dbl> <chr>  <dbl> <lgl> <lgl>  <dbl>
## 1  15.4  43.0 1        19 black    1.5 NA    NA       0.5
## 2  15.4  43.0 2        19 black    1.5 NA    NA       0.5
last_plot() +
  aes(color = dist > 30)

Closing remarks, Other Relevant Work, Caveats