rggmosaic

In R language package `ggmosaic`, how to add weight percent label to the columns


In package ggmosaic, how to add weight percent label to the columns ? I want to add the percent value of each column (every column totla percent equalt 100%). Thanks!

library(tidyverse)
library(ggmosaic)

ggplot(data = titanic) +
  geom_mosaic(aes(x = product(Class), fill = Survived)) +
  geom_mosaic_text(size=5,aes(x = product(Class), fill = Survived))

Solution

  • you can use ggplot_build to calculate the percentage per class of each total count values like this:

    library(tidyverse)
    library(ggmosaic)
    
    p <- ggplot(data = titanic) +
      geom_mosaic(aes(x = product(Class), fill = Survived)) +
      geom_mosaic_text(size=5,aes(x = product(Class), fill = Survived))
    
    p + geom_text(data = ggplot_build(p)$data[[1]] %>% 
                    group_by(x__Class) %>%
                    mutate(pct = .wt/sum(.wt)*100), 
                  aes(x = (xmin+xmax)/2, y = (ymin+ymax)/2, label=round(pct, 2)))
    

    Created on 2022-12-22 with reprex v2.0.2