0

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.

plicht
  • 123
  • 6
  • 2
    Use `p = p + facet_grid(~ subject, scales = "free")` ? – Ronak Shah Jun 16 '21 at 10:27
  • With your code I am getting the groupings you ask for. Apart from the typo in *nonlesoinal* (*oi* for *io* in the last row). – Rui Barradas Jun 16 '21 at 10:36
  • Sorry, I am new to this forum. I am looking for a way to goup bars specific to subjects within the respective facets. Bar grouping performed like in this post [link] (https://stackoverflow.com/questions/46597278/how-to-plot-a-stacked-and-grouped-bar-chart-in-ggplot/46597859#46597859) but with facects included. – plicht Jun 16 '21 at 10:40

0 Answers0