This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Coord_flip in R

Hello! Please help me. I'm new to R.

I wanted to make a horizontal stacked bar plot and I've tried placing the "coord_flip" code in my barplot code but I can't seem to get the horizontal orientation. Here is the data/code that I've used. Thank you!

library (ggplot2)

dat <- read.table(text = "Bin018   Bin038   Bin095   Bin029   Bin031
Polyketide 3 2 2 6 1   
Non-Ribosomal_Peptides 1 8 6 9 7   
Terpenoids 5 1 0 1 0  
Anti-microbial_Peptides 3 2 4 5 8", header = TRUE)



dat <- barplot (as.matrix(dat),
         main = "Cyanobacterial SM Biosynthesis Genes",
         xlab = "TSF Cyanobacterial MAGs", ylab = "Abundance",
         col=c("cyan1","coral1","seagreen2","mediumpurple1"),
         legend.text = rownames(dat),
         args.legend = list(title = "Secondary Metabolites", x = "topleft",
                            inset = c(0.05, 0))) +
  coord_flip()

enter image description here

graph stacked r plot bar

3 answers

It does not work because barplot() is a base R plotting routine, not a ggplot one, so the + is not doing anything. See http://www.sthda.com/english/wiki/ggplot2-barplots-quick-start-guide-r-software-and-data-visualization to get started with ggplot syntax for barplots.

I see, thank you for your response and suggestion! :D

the barplot is not from ggplot2 package. I think you are supposed to use geom_bar with coord_flip like here

Thanks for the tip! :D

You don't need ggplot , remove `+ coord_flip()' and optimize legend display. Try following code:

par(mar=c(6,8,4,0))
barplot (as.matrix(dat),
         main = "Cyanobacterial SM Biosynthesis Genes",
         col=c("cyan1","coral1","seagreen2","mediumpurple1"),
         legend.text = rownames(dat),
         args.legend = list(title = "Secondary Metabolites", x = "bottomright",
                            inset = c(0.05, 0)),
         las=1, horiz = T, 
         )
mtext("Abundance", side=2, line=5, cex = 2)
mtext("TSF Cyanobacterial MAGs", side=1, line=4, cex = 2)

barplot

Thank you so much for your time and help, cpad0112! It worked perfectly! :D

Log in to answer this question.