I would like to create a stacked barplot with groupings within a facet grid. My Data looks like this:
Sample | subject | staging | Species | Abundance% |
---|---|---|---|---|
sample1 | 1 | Patch | A | 100 |
sample2 | 1 | Plaque | B | 50 |
sample2 | 1 | Plaque | A | 50 |
sample3 | 1 | nonlesional | C | 100 |
sample4 | 1 | nonlesional | A | 100 |
sample5 | 2 | Patch | A | 100 |
sample6 | 2 | Patch | B | 100 |
sample7 | 2 | nonlesional | C | 100 |
sample8 | 2 | nonlesoinal | A | 100 |
I already created his stacked barplot with facet_grid using the following code:
mdf = read.tsv("XXX.tsv")
p = ggplot(mdf, aes_string(x = "Sample", y = "Abundance", fill = "Species")
p = p + geom_bar(stat = "identity", position = "stack", color = "black")
p = p + theme(axis.text.x = element_text(angle = -90, hjust = 0))
p = p + facet_grid(~staging, scales = "free")
p
Now I want to reorganize the bars from each sample to the respective subject within the facet_grid to achieve a better overview. E. g., using above example, sample3 and sample4 belong to subject 1 an should be grouped together in the facet "nonlesional" as sample7 and sample8 should be grouped to subject 2 in the same facet.
I tried several times but did not figuere out how to achieve this.