ChiLiubio / microeco

An R package for data analysis in microbial community ecology
GNU General Public License v3.0
195 stars 56 forks source link

How to re order sample ID in a barplot #344

Closed srisvs33 closed 6 months ago

srisvs33 commented 6 months ago

Hi @ChiLiubio

I was able to reorder the groups according to the example given in the tutorial (https://chiliubio.github.io/microeco_tutorial/notes.html#group-order). However, I need to reorder sample IDs (sample names) in a barplot.

Here is the code that I have used for .. However, it did'n change as per my given order. Any suggestions on how to change the sample order asper custom list.

Thank you very much Venkat

Code

meco_dataset$sample_table$Sample_type %<>% factor(., levels = c("PA", "FL"))

str(dataset$sample_table)

meco_dataset$sample_table$Hydrography %<>% factor(., levels = c("TPDW", "FZ","AW"))

str(dataset$sample_table)

meco_dataset$sample_table$SampleID%<>% factor(., levels = c("3A","4A","11A","12A","15A","16A","19A","20A","27A","28A","31A","32A","35A","36A","39A","40A","43A","44A","47A","48A","51A","52A","55A","56A","59A","60A","3B","4B","11B","12B","15B","16B","19B","20B","23B","24B","27B","28B","31B","32B","35B","36B","39B","40B","43B","44B","47B","48B","51B","52B","55B","56B","59B","60B")) str(dataset$sample_table)

t1 <- trans_abund$new(dataset = meco_dataset, taxrank = "Phylum", ntaxa = 7)

PC53 = t1$plot_bar(color_values = paletteer_d("ggsci::category10_d3"),others_color = "grey70", facet = c("Sample_type", "Hydrography"), xtext_keep = TRUE, legend_text_italic = TRUE, barwidth = 0.8) +theme_classic()

print(PC53) ggsave('test4.jpeg', units="in", width=20, height=7, dpi=600)

test4

ChiLiubio commented 6 months ago

Hi Venkat, The easiest way is to use order_x parameter in plot_bar function. Let me show an example.

library(microeco)
library(ggplot2)
t1 <- trans_abund$new(dataset = dataset, taxrank = "Phylum", ntaxa = 7)

t1$plot_bar(facet = c("Group", "Type"), xtext_angle = 30, xtext_size = 8)
ggsave('test1.jpeg', units="in", width = 20, height = 7)

t1$plot_bar(facet = c("Group", "Type"), order_x = rev(rownames(dataset$sample_table)), xtext_angle = 30, xtext_size = 8)
ggsave('test2.jpeg', units="in", width = 20, height = 7)

We can see, in figure test2, the order of x axis has a reverse direction within each fixed facet. Another way is to assign factor levels in t1$data_abund$Sample. The reason that you failed to make meco_dataset$sample_table$SampleID to be factors is the name of x axis comes from converted rownames of sample_table (i.e., t1$data_abund$Sample), not the SampleID of sample_table. The design reason is many users donot have a habit to add a SampleID column in the sample_table. Thus I have to add a parameter to control this.

Best, Chi

srisvs33 commented 6 months ago

Dear @ChiLiubio Thanks for the tip... iIwas able to re order the samples