【问题标题】:Making stack bar plot of bacterial abundance制作细菌丰度的堆叠条形图
【发布时间】:2016-11-21 23:55:51
【问题描述】:

我有一个包含 152 个样本(行)的相对细菌丰度的数据框。我想绘制所有样本中每个细菌组的总体丰度的堆积条形图(例如放线菌与拟杆菌与厚壁菌等)。 ) 我希望它用颜色编码,并带有一个图例。有人可以建议如何做到这一点吗?我的问题是我不确定如何获得在 R 中绘制的列总数。谢谢。

row.names       Actinobacteria  Bacteroidetes   Firmicutes  Fusobacteria    Proteobacteria  Verrucomicrobia Other
1   sample1 0.0084246282    0.41627099  0.55475503  0.000000e+00    7.245180e-04    5.391762e-05    1.977092e-02
2   sample2 0.0168571327    0.13298800  0.80289437  3.560112e-05    4.272135e-03    4.238314e-02    5.696180e-04
3   sample3 0.0020299288    0.53813817  0.42367947  3.311006e-02    7.978327e-04    3.534702e-05    2.209189e-03

【问题讨论】:

标签: r plot bar-chart


【解决方案1】:

我不清楚样本名称是否是数据框中的行名称,所以我只是重新创建了数据框,将样本名称放入变量中,与细菌名称相同:

Sample Actinobacteria Bacteroidetes Firmicutes Fusobacteria Proteobacteria
1 sample1    0.008424628     0.4162710  0.5547550 0.000000e+00   0.0007245180
2 sample2    0.016857133     0.1329880  0.8028944 3.560112e-05   0.0042721350
3 sample3    0.002029929     0.5381382  0.4236795 3.311006e-02   0.0007978327
  Verrucomicrobia       Other
1    5.391762e-05 0.019770920
2    4.238314e-02 0.000569618
3    3.534702e-05 0.002209189

要重现此数据集,您可以运行以下命令:

df <- structure(list(Sample = structure(1:3, .Label = c("sample1", 
"sample2", "sample3"), class = "factor"), Actinobacteria = c(0.0084246282, 
0.0168571327, 0.0020299288), Bacteroidetes = c(0.41627099, 0.132988, 
0.53813817), Firmicutes = c(0.55475503, 0.80289437, 0.42367947
), Fusobacteria = c(0, 3.560112e-05, 0.03311006), Proteobacteria = c(0.000724518, 
0.004272135, 0.0007978327), Verrucomicrobia = c(5.391762e-05, 
0.04238314, 3.534702e-05), Other = c(0.01977092, 0.000569618, 
0.002209189)), .Names = c("Sample", "Actinobacteria", "Bacteroidetes", 
"Firmicutes", "Fusobacteria", "Proteobacteria", "Verrucomicrobia", 
"Other"), class = "data.frame", row.names = c("1", "2", "3"))

正如@zx8754 所建议的,此数据帧需要重新整形,即从宽格式转换为长格式。有关更多信息,请查看此link 以获取一些示例。

如果上面的数据框被命名为df,下面的命令将把它改成长格式:

library(reshape2)
df_long <- melt(df, id.vars = "Sample", variable.name = "Phyla")

从这里我们可以使用 ggplot 进行绘图:

library(ggplot2)
ggplot(df_long, aes(x = Sample, y = value, fill = Phyla)) + 
    geom_bar(stat = "identity")

给出:

【讨论】:

  • 谢谢。有没有办法改变它,让图例标题说“Phyla”而不是变量?
  • 当然,variable 只是在df_long 中保存细菌名称的列的名称。如果您更改数据框中该列的名称,则图例标题将相应更改。或者,您可以直接在melt 过程中更改它。我编辑了代码以添加它。
  • 或者您可以更改实际的图例标题而不对数据做任何事情:cookbook-r.com/Graphs/Legends_%28ggplot2%29
猜你喜欢
  • 2020-05-05
  • 1970-01-01
  • 1970-01-01
  • 2014-12-28
  • 2022-11-23
  • 1970-01-01
  • 2023-01-31
  • 1970-01-01
  • 2022-01-21
相关资源
最近更新 更多