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))