Adding counts to ggmosaic, can this be done simpler?

前端 未结 2 1001
慢半拍i
慢半拍i 2021-01-12 02:27

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

2条回答
  •  青春惊慌失措
    2021-01-12 03:01

    I've previously made similar charts in pure ggplot2, without using the ggmosaic package. I don't know if this would be sufficient for your use case, though:

    # data manipulation
    data %>%
      group_by(a, b) %>%
      summarise(n = n()) %>%
      mutate(x.width = sum(n)) %>%
    
      # simulate mosaic plot
      ggplot(aes(x = factor(a), y = n)) +
      geom_col(aes(width = x.width, fill = factor(b)),
               colour = "white", size = 1, position = position_fill(reverse = TRUE)) +
      geom_label(aes(label = n),
                 position = position_fill(vjust = 0.5)) +
      facet_grid(~ a, space = "free", scales = "free", switch = "x") +
    
      # cosmetic tweaks
      scale_x_discrete(name = "a") +
      scale_y_continuous(labels = scales::percent) +
      theme(axis.text.x = element_blank(),
            axis.ticks.x = element_blank(),
            axis.title.y = element_blank(),
            strip.background = element_blank(),
            panel.spacing = unit(0, "pt"))
    

提交回复
热议问题