R 了解ggplot条形图上样本的顺序
请参见下面的编辑 我是df的条形图,由440行组成,结构如下: 然后,我使用以下代码创建条形图:R 了解ggplot条形图上样本的顺序,r,ggplot2,facet-wrap,R,Ggplot2,Facet Wrap,请参见下面的编辑 我是df的条形图,由440行组成,结构如下: 然后,我使用以下代码创建条形图: 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_cartes
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)
这给了我一个数字:
我注意到患者编号不正确,因为p_10位于p_1之后的第二位。我是否可以更改图像,使顶行为P_1至P_5,底行为P_6至P_10
另外,我注意到,对于p_8,样本也出现了问题,它们应该是P8W0、P8W2、P8W4、P8W12、P8W14。我也可以重新订购吗
编辑:我通过添加以下内容修复了刻面排序的问题:
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)
但我不确定如何更改pU8样本的顺序将
SampleID
转换为因子
:
ggplot(fplot2, aes(x = factor(SampleID, levels = lvls), y = Abundance, fill = Taxon))
并使用所需的顺序明确指定lvls
。以下是我对图像中给定轴标签所需顺序的最佳猜测:
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))
)
如果您包含一个简单的示例输入和所需的输出,可以用来测试和验证可能的解决方案,那么就更容易为您提供帮助。数据图片没有帮助,因为我们无法将其复制/粘贴到R中。也许可以为您的问题制作一个较小的子集。条形图的顺序通常由变量的级别顺序决定。因此,请确保SampleID列按您想要的方式排列级别。
[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"