1

I am using R to make a relative abundance plot.

I import data from .xlsx, melt it, then plot two data sets and combine them with ggplot using something like the code below.

jengraph.CEC <- ggplot() + 
  geom_bar(aes(y = Percentage, x = Sample, fill = Phyla), 
           data = datamCECMORPH.df, stat="identity") + 
  geom_bar(aes(y = Percentage, x = Sample, fill = Phyla), 
           data = datamCECSEQ.df, stat="identity") + 
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) + 
  scale_y_continuous(expand = c(0,0)) 

It works, however the order that the "sample" column is not preserved and is alphabetized.

I am able to use the factor function to set the order per all the examples that I have seen i.e.

datamCECMORPH.df$Sample <-factor(datamCECMORPH.df$Sample, 
   levels=datamCEC.df[order(datamCECMORPH.df$Sample), "Sample"])
...

So I can get the order to work for one of the data sets and can plot it correctly, however when I try to apply this to both data sets and plot them together, it reverts to alphabetical.

Does anyone have any ideas? Is there an overriding x-axis order that I'm missing in ggplot?

Gregor Thomas
  • 119,032
  • 17
  • 152
  • 277
  • 4
    Could you please either include your data, or reproduce your problem with a built in dataset? It's easier for people to help if they can run your code and reproduce the problem. See [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for guidance on how to easily include data in questions – Jan Boyer Jun 06 '18 at 19:06
  • Make sure your two data sets have the same factor levels in the same order. It sounds like maybe there are some levels present in one but not the other, which causes an internal re-factoring. – Gregor Thomas Jun 06 '18 at 20:24

0 Answers0