简体   繁体   中英

Understanding the ordering of samples on a ggplot bar plot

SEE EDIT BELOW

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

在此处输入图片说明

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:

在此处输入图片说明

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM