I am trying to create a grouped and stacked bar chart that shows proprtions by a group and then further differentiated by another group. I would like my chart to look something like this But all of my code shows my chart like this This feels like a very silly problem because proportions are so simple but I really can not make it grouped by main groups and then by two different groups and then stacked by subgroups.
My data is here
I tried:
figure4 <- figure1_edit %>%
summarise(N = n(), .by = c(group, carbon_chain, `Functional Group`)) |>
mutate(
prop = (N / sum(N))*100,
x = paste0(group, "n", carbon_chain),
.by = c(group)
) %>%
ggplot(aes(y = carbon_chain, x = prop, fill = `Functional Group`)) +
geom_bar(stat = "identity", position = "fill") +
scale_x_continuous(labels = scales::percent_format(scale = 1)) +
facet_grid(~ group) +
scale_fill_brewer(palette = "Set3") +
theme_bw()
figure4
But this gave me the figure that is not correctly differentiated. So then I tried to create sub groups by the original groups (so in this example I just tried the ‘rain’ group), calculate the proportions needed, but this still gave me my incorrect chart.
I would like it to be grouped by ‘group’ (so essentially 3 different bar charts) and then within each group, grouped by the chain length (short vs long) and the % of short and long found per the ‘group’ of interest, and within each chain length further filled by the % of functional group per each chain length group.
Irena Pavlovic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.