-3

SEE EDIT BELOW

I am bar plot from a df which consists of 440 rows and is structured like so:

enter image description here

I then use the following code to create a barplot:

ggplot(fplot2, aes(x=SampleID, y=Abundance, fill=Taxon)) +
geom_bar(stat="identity") +
scale_fill_manual(values = Cb64k) +
theme(axis.text.x = element_text(angle=45, hjust=1)) +
coord_cartesian(expand=FALSE) +
xlab("Sample") +
ylab("Abundance") +
facet_wrap(~fplot2$Patient, scales="free_x", nrow=2, ncol=5)

Which gives me this figure:

enter image description here

I noticed that the patient numbers are not correct, as P_10 is second after P_1. Can I change the image so that the top row is P_1 to P_5 and the bottom row is P_6 to P_10?

Also, I noticed that for P_8 the samples are also out of order, they should be P8W0, P8W2, P8W4, P8W12, P8W14. Can I reorder that as well?

EDIT: I fixed the issue with the facet ordering by adding:

facet_wrap(~factor(fplot2$Patient,levels=c("P_1","P_2","P_3","P_4","P_5","P_6","P_7","P_8","P_9","P_10")), scales = "free_x", nrow=2, ncol=5)

But I'm not sure how to change the order of the P_8 samples

mrad
  • 173
  • 1
  • 11
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Pictures of data aren't helpful because we can't copy/paste that into R. Perhaps make a smaller subset for your question. The order of bars is typically determined by the order of levels of your variables. So make sure your SampleID column has the levels ordered in the way you want. – MrFlick Oct 20 '20 at 02:22

1 Answers1

0

Convert SampleID into a factor as well:

ggplot(fplot2, aes(x = factor(SampleID, levels = lvls), y = Abundance, fill = Taxon))

And explicitly specify the lvls with your desired order. Here is my best guess of the order you want given the axis labels in your image:

lvls <- c(
  vapply(1:6, function(x) paste0("P", x, "W", c(0, 1, 3, 6)), character(4L)), 
  paste0("P7W", c(0, 3, 6)), 
  paste0("P8W", c(0, 2, 4, 12, 14)), 
  vapply(9:10, function(x) paste0("P", x, "W", c(0, 1, 3, 6)), character(4L))
)

The lvls vector looks like this

 [1] "P1W0"  "P1W1"  "P1W3"  "P1W6"  "P2W0"  "P2W1"  "P2W3"  "P2W6"  "P3W0"  "P3W1"  "P3W3"  "P3W6"  "P4W0"  "P4W1"  "P4W3"  "P4W6"  "P5W0"  "P5W1"  "P5W3"  "P5W6"  "P6W0" 
[22] "P6W1"  "P6W3"  "P6W6"  "P7W0"  "P7W3"  "P7W6"  "P8W0"  "P8W2"  "P8W4"  "P8W12" "P8W14" "P9W0"  "P9W1"  "P9W3"  "P9W6"  "P10W0" "P10W1" "P10W3" "P10W6"
ekoam
  • 8,744
  • 1
  • 9
  • 22