Search code examples
rggplot2ggmosaic

Adding counts to ggmosaic, can this be done simpler?


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 of the code quite ugly. Do you have any suggestions on how I can improve the code, to make it more reusable?

Especially the need for storing an early version of the plot in a temporary variable seems wrong compared to what usually can be achieved using ggplot2.

library(tidyverse)
library(ggmosaic)
#> Indlæser krævet pakke: productplots
#> 
#> Vedhæfter pakke: 'ggmosaic'
#> De følgende objekter er maskerede fra 'package:productplots':
#> 
#>     ddecker, hspine, mosaic, prodcalc, spine, vspine

data <- tribble(~a, ~b, 
                1, 1, 
                1, 1, 
                1, 1, 
                1, 2, 
                2, 1,
                2, 2, 
                3, 2)

p <- ggplot(data) + 
  geom_mosaic(aes(x=product(b, a), fill=as.factor(b)))

p + 
  geom_label(data = ggplot_build(p)$data %>% as.data.frame() %>% filter(.wt > 0), 
             aes(x = (xmin + xmax)/2, 
                 y = (ymin + ymax)/2, 
                 label = .wt))

Created on 2018-05-08 by the reprex package (v0.2.0).


Solution

  • This can be done with a single line of code using the inbuilt labelling functionality of the ggmosaic package.

    To do so we simply add the geom_mosaic_text() layer:

    data <- tribble(~a, ~b, 
                    1, 1, 
                    1, 1, 
                    1, 1, 
                    1, 2, 
                    2, 1,
                    2, 2, 
                    3, 2) %>%
      mutate(across(c(a, b), as.factor))
    
    ggplot(data) + 
      geom_mosaic(aes(x=product(b, a), fill=b)) +
      geom_mosaic_text(aes(x = product(b, a), label = after_stat(.wt)), as.label=TRUE)
    

    Labelled mosaic plot