rggmosaic

geom_mosaic_text returns nothing


In the code below, I want to add a label to the mosaic plot, but geom_mosaic_text returns nothing. Can anyone help with this?

library(tidyverse)
library(ggmosaic)

df <- diamonds  %>%  
  summarise(sumx = sum(x), .by = c(cut, color))

ggplot(data = df) +
  geom_mosaic(aes(x = product(cut), fill = color, weight = sumx))
geom_mosaic_text(aes(x = product(cut), fill = color, label=sumx))

Solution

  • You need to add sumx as weight to mapping in geom_mosaic_text, same as in geom_mosaic, then use the weight with after_stat to label:

    ggplot(data = df) +
      geom_mosaic(aes(x = product(cut), fill = color, weight = sumx)) +
      geom_mosaic_text(aes(x = product(cut), fill = color, weight = sumx, label = after_stat(.wt)))