r - 了解 ggplot 条形图上样本的顺序
问题描述
请参阅下面的编辑
我是来自 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_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)
但我不确定如何更改 P_8 样本的顺序
解决方案
也转换SampleID
成a factor
:
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))
)
lvls
矢量看起来像这样
[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"
推荐阅读
- c# - Unity 中的加速
- reactjs - 使用 Ejected Create React App 设置同构 SSR 的教程
- vba - 在VBA中从A2删除行到列的末尾
- java - 使用简单的 txt 文件进行 Selenium 参数化的黄瓜
- azure-data-lake - 如何在不使用 Visual Studio 的情况下在 Microsoft azure 数据分析中引用用户定义的运算符 (UDO)
- excel - 可以从选择中确定数据透视字段的位置吗?
- python - 拆分字符串时出现AttributeError
- mysql - 如何使用 mysqli 加速此查询?
- javascript - 使用构造函数和类 JavaScript
- bash - Bash:Nginx 版本检查剪切