I would like to make a mosaic plot using the ggmosaic package and add the counts as shown in the example below.
The example sort of works, but I find the structure o
Here's a way to do this using the supplied code, but without needing to save a temporary plot. It makes use of ggplot's last_plot
to access the plot object up to the most recent '+', and also accesses the data a bit more simply using layer_data
, rather than ggplot_build
.
library(tidyverse)
library(ggmosaic)
data <- tribble(~a, ~b,
1, 1,
1, 1,
1, 1,
1, 2,
2, 1,
2, 2,
3, 2)
data <- data %>%
mutate(across(c(a, b), as.factor))
ggplot(data) +
geom_mosaic(aes(x=product(b, a), fill=b)) +
geom_label(data = layer_data(last_plot(), 1) %>% filter(.wt > 0),
aes(x = (xmin + xmax) / 2,
y = (ymin + ymax) / 2,
label = .wt))
Created on 2020-07-05 by the reprex package (v0.3.0)
It's still a hack, but it will save you the pain of assigning a temporary plot.