2017-05-19 63 views
1

生物学家和ggplot2初学者在这里。我有一个相对较大的DNA序列数据集(数百万个短DNA片段),我首先需要对每个序列的质量进行过滤。我想说明使用ggplot2时,有多少读数通过堆积条形图进行过滤。ggplot2中堆叠barplot的重排因子

我已经想通了,ggplot喜欢在长格式的数据,并已成功地与熔体功能格式化也从reshape2

这就是数据的子集看起来像此刻:

library sample filter value 
LIB0 0011a F1 1272707 
LIB0 0018a F1 1505554 
LIB0 0048a F1 1394718 
LIB0 0095a F1 2239035 
LIB0 0011a F2 250000 
LIB0 0018a F2 10000 
LIB0 0048a F2 10000 
LIB0 0095a F2 10000 
LIB0 0011a P 2118559 
LIB0 0018a P 2490068 
LIB0 0048a P 2371131 
LIB0 0095a P 3446715 
LIB1 0007b F1 19377 
LIB1 0010b F1 79115 
LIB1 0011b F1 2680 
LIB1 0007b F2 10000 
LIB1 0010b F2 10000 
LIB1 0011b F2 10000 
LIB1 0007b P 290891 
LIB1 0010b P 1255638 
LIB1 0011b P 4538 

库和样本是我的ID变量(相同的样本可以在多个库中)。 'F1'和'F2'意味着在这一步骤中这些读数被过滤掉了,'P'表示过滤后剩余的序列读数。

我已经想出了如何制作一个基本的堆叠barplot,但现在我遇到了麻烦,因为我无法弄清楚如何正确地重新排列x轴上的因子,以便在基于图的降序中对条进行排序在F1,F2和P.方式的总和,现在我认为他们是基于样品名称

testdata <- read.csv('testdata.csv', header = T, sep = '\t') 

ggplot(testdata, aes(x=sample, y=value, fill=filter)) + 
    geom_bar(stat='identity') + 
    facet_wrap(~library, scales = 'free') 

enter image description here

一些google搜索后,我发现了关于聚合函数库中按字母顺序保存给我每个样本库的总数:

aggregate(value ~ library+sample, testdata, sum) 

    library sample value 
1 LIB1 0007b 320268 
2 LIB1 0010b 1344753 
3 LIB0 0011a 3641266 
4 LIB1 0011b 17218 
5 LIB0 0018a 4005622 
6 LIB0 0048a 3775849 
7 LIB0 0095a 5695750 

虽然这确实给了我总数,但我现在不知道如何使用它来重新排序因素,尤其是因为有两个我需要考虑的(库和样本)。

所以我想我的问题归结为: 如何根据每个图书馆的F1,F2和P的总数,在我的图表中订购我的样本?

非常感谢您为我提供的指点!

+1

莫非[这从SO(HTTP://计算器.com/questions/36438883/reorder-stacks-in-horizo​​ntal-stacked-barplot-r?rq = 1)对你有帮助吗? – KoenV

回答

1

你快到了。你需要根据汇总数据,以改变testdata$sample因子水平(我想没有样品名称中均出现LIB1和lib0):

df <- aggregate(value ~ library+sample, testdata, sum) 

testdata$sample <- factor(testdata$sample, levels = df$sample[order(-df$value)]) 

ggplot(testdata, aes(x=sample, y=value, fill=filter)) + 
    geom_bar(stat='identity') + 
    facet_wrap(~library, scales = 'free') 

enter image description here

+0

完美无瑕!我很感激帮助,非常感谢! – Sam