help with facet grid ggplot2

Hi everyone,
I used the following command for visualizing microbiome relative abundance
ggplot(mdata_class, aes(x = Sample.ID, y = Abundance, fill = Class)) +
geom_bar(stat = "identity") +
scale_fill_manual(values = class_colors) +
scale_x_discrete(
breaks = map$Sample.ID,
labels = map$Sample.ID,
drop = FALSE
) +
theme(axis.title.x = element_blank(),
axis.text.x=element_text(angle=90,hjust=1,vjust=0.5)) +
guides(fill = guide_legend(reverse = TRUE, keywidth = 1, keyheight = 1)) +
facet_grid(~Health.state) +
ylab("Relative Abundance (Class > 1%) \n") +
ggtitle("Class Composition of microbiome data per individual")

facet_grid was used to separate samples to each category based on health status, however, the bar plot resulted from the command looks like:

my question
How to make the bar plot for each category (healthy or patient) include only its samples?
thank u in advance

could you also provide an example dataset? So we can better understand how your dataset is structured and better understand the problem

1 Like

It is a long script for microbiome analysis
at first phyloseq object was created from Mothur outputs

and the following is the head of data used for abundance analysis

OTU Sample Abundance Sample.ID Health.state Gender Age Kingdom
1 Otu0005 M_33 0.3928287 M_33 healthy Male 35 Bacteria
2 Otu0005 M_18 0.3257779 M_18 healthy Male 42 Bacteria
3 Otu0005 M_29 0.3191535 M_29 healthy Male 44 Bacteria
4 Otu0005 M_11 0.2677918 M_11 patient Female 21 Bacteria
5 Otu0005 M_20 0.2635487 M_20 healthy Female 33 Bacteria
6 Otu0005 M_31 0.2407429 M_31 healthy Male 32 Bacteria
Phylum Class
1 Actinobacteria Actinobacteria
2 Actinobacteria Actinobacteria
3 Actinobacteria Actinobacteria
4 Actinobacteria Actinobacteria
5 Actinobacteria Actinobacteria
6 Actinobacteria Actinobacteria

1 Like

As said above, without an reproducible example we cannot test it, but I speculate it's the drop = FALSE in the scale_x_discrete call. Replace this with drop = TRUE.
Actually, you probably wont need the scale_x_discrete at all, as this adds the breaks and labels that should be there anyway.

1 Like

I can also suggest to try facet_grid(~Health.state, scales = "free_x").
Note, this solution and probably solution suggested by @Matthias will work only if you have one row.

1 Like

thank you @Dobrokhotov1989
it works well