library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.5     ✓ purrr   0.3.4
## ✓ tibble  3.1.6     ✓ dplyr   1.0.8
## ✓ tidyr   1.0.2     ✓ stringr 1.4.0
## ✓ readr   1.3.1     ✓ forcats 0.5.0
## Warning: package 'ggplot2' was built under R version 3.6.2
## Warning: package 'tibble' was built under R version 3.6.2
## Warning: package 'purrr' was built under R version 3.6.2
## Warning: package 'dplyr' was built under R version 3.6.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
tidytitanic::tidy_titanic %>%
  count(sex, survived) %>% 
  ggplot() + 
  aes(sex, survived) + 
  geom_text(aes(label = n))

tidytitanic::tidy_titanic %>%
  count(sex, survived) %>% 
  ggplot() + 
  aes(x = 0, y = 0) + 
  facet_grid(rows = vars(sex), cols =  vars(survived)) +
  geom_text(aes(label = n))

last_plot() %>% layer_data()
##   x y label PANEL group colour size angle hjust vjust alpha family fontface
## 1 0 0  1364     1    -1  black 3.88     0   0.5   0.5    NA               1
## 2 0 0   367     2    -1  black 3.88     0   0.5   0.5    NA               1
## 3 0 0   126     3    -1  black 3.88     0   0.5   0.5    NA               1
## 4 0 0   344     4    -1  black 3.88     0   0.5   0.5    NA               1
##   lineheight
## 1        1.2
## 2        1.2
## 3        1.2
## 4        1.2
tidytitanic::tidy_titanic %>%
  count(sex, survived, age) %>% 
  ggplot() + 
  aes(x = 0, y = 0) + 
  facet_grid(rows = vars(sex, age), cols =  vars(survived)) +
  geom_text(aes(label = n))

compute_layer_count_table <- function(data, scales){
  
  data %>% 
    mutate(label = n(),
           x = 0,
           y = 0 ) %>% 
    distinct()
  
}

StatLayercount <- ggplot2::ggproto(
  `_class` = "StatLayercount",
  `_inherit` = ggplot2::Stat,
  required_aes = c("x", "y"),
  compute_group = compute_layer_count_table
  )

geom_text_layer_count <- function(
  mapping = NULL,
  data = NULL,
  position = "identity",
  na.rm = FALSE,
  show.legend = NA,
  inherit.aes = TRUE, ...) {
  ggplot2::layer(
    stat = StatLayercount,  # proto object from step 2
    geom = ggplot2::GeomText,  # inherit other behavior
    data = data,
    mapping = mapping,
    position = position,
    show.legend = show.legend,
    inherit.aes = inherit.aes,
    params = list(na.rm = na.rm, ...)
  )
}

tidytitanic::tidy_titanic %>%
  ggplot() + 
  aes(x=0, y= 0) +
  facet_grid(rows = vars(sex, age), cols =  vars(survived)) +
  geom_text_layer_count( )

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.