Coord_flip in R
3
1
Entering edit mode
2.4 years ago
amy ▴ 20

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 • 2.1k views
ADD COMMENT
1
Entering edit mode
2.4 years ago
ATpoint 81k

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.

ADD COMMENT
0
Entering edit mode

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

ADD REPLY
1
Entering edit mode
2.4 years ago
asalimih ▴ 60

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

ADD COMMENT
0
Entering edit mode

Thanks for the tip! :D

ADD REPLY
1
Entering edit mode
2.4 years ago

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

ADD COMMENT
0
Entering edit mode

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

ADD REPLY

Login before adding your answer.

Traffic: 2472 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6