Sorting Samples by Metadata (get rid of default alphabetical order) - meyermicrobiolab/Meyer_Lab_Resources GitHub Wiki

The default order of items in a ggplot2 is alphabetical. Many times you will want to sort samples by your own scheme. To do this, you need to make a factor from the column of metadata that you want to order your way (here it is "Month"). Note, this is how to do it for sample data in a phyloseq object ("ps" in the example below). In a phyloseq object, IT IS NOT POSSIBLE TO DO THIS WITH SAMPLE NAMES! This is a quirk of phyloseq.

sample_data(ps)$Month<-factor(sample_data(ps)$Month,levels=c("February 2013","August 2014"))

If you want to sort samples/groups with just ggplot2 (not using phyloseq object), it would be a similar format:

dataframe$column <- factor(dataframe$column, levels = c("this", "that", "the other"))

What if you want to get rid of certain samples by metadata? See this trick