1
votes

Is there any way to create subgroups for stacked bar charts in R? Below is an example of what I'm aiming for.

Example of What I'm Aiming to Plot

I'm currently using the below code - but I can't figure out how to sub-group the samples (identified by the ID column) by their larger arching group (Sample Site)

ggplot(PFASData, aes(fill=Species, y=value, x=ID)) + geom_bar(position="stack", stat="identity")

Resulting Plot

1
Seems like a facet with 0-width spacing would do the trick.teunbrand

1 Answers

0
votes

Here's a small example that shows grouping by subgroup (here cyl) with stacked bars. By using scales = "free_x", space = "free_x" we can get equal width bars within varying-width subgroups.

ggplot(mtcars, aes(as.character(cyl), wt, fill = as.character(mpg))) +
  geom_col() +
  facet_grid(.~gear, scales = "free_x", space = "free_x") +
  guides(fill = "none") +
  theme_minimal()

enter image description here