0

I'm struggling to create labels for percentages in my. mosaic plot using geom_mosaic chart.

Here's my code. I got it to work for counts, but don't know how to transform it so the labels are %.

p <- ggplot(df) +
  geom_mosaic(aes(x = product(gender, race), fill = gender)) +
  scale_y_continuous(labels = scales::percent, breaks = scales::pretty_breaks(n = 5)) +
  theme(
    axis.title = element_text(size = 14),
    title = element_text(size = 14, face = "bold"),
    plot.subtitle = element_text(face = "plain"),
    axis.ticks = element_blank(),
    panel.grid = element_blank()
  ) +
  scale_fill_manual(values = colours) +
  labs(title = "race and gender", fill = "gender") +
  theme(strip.text.x = element_text(size = 20))


# Adding Labels of counts
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
  )
) + 
  guides(fill = guide_legend(reverse = TRUE))

Picture of output

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
  • 1
    Please elaborate how you want to calculate the percentages. (e.g. overall? by each race / gender?) Also, I see your code includes aesthetic mapping for `fill`, but your plot doesn't show any distinction by fill. If you can make your problem reproducible by providing your data (or using a commonly available dataset such as titanic, which I believe is used by ggmosaic's own examples), that would likely get you better advice. – Z.Lin Apr 13 '23 at 03:56

0 Answers0