多变量时间序列绘图:细菌样本分组可视化方案问询
问题描述
我有一个dataframe,第一列是不同细菌种类,其余列为样本,每个样本对应特定时间点(T0、T1…),最后39列为对照组。我需要为每种细菌单独绘图,X轴为不同时间点,Y轴为数值,拟使用带误差线的柱状图或箱线图,请问如何按时间和细菌对数据进行分组?
数据示例
structure(list(Bacteria = c("Methanobrevibacter", "Methanosphaera", "Methanomassiliicoccus"), PIE2001_T0_TORUNDA = c(2.279974027, 0.670536115, -0.022611066), PIE2001_T1_TORUNDA = c(2.021643324, -0.057798217, -0.057798217), PIE2001_T5_COMPL = c(2.788566988, 0.648500825, -0.044646356), PIE2006_T0_TORUNDA = c(0.07550014, 1.684938052, 0.07550014), PIE2007_T0_TORUNDA = c(2.072075243, 1.261145027, -0.125149334), PIE2007_T1_TORUNDA = c(2.601582257, 1.279826417, -0.106467944), PIE2007_T2 = c(2.81564899, 1.765826865, -0.180083284), PIE2007_T3 = c(0.639040509, 3.081387545, -0.054106671 ), PIE2013_T0_COMPLETA = c(2.683794403, -0.024255798, -0.024255798 ), PIE2013_T1_COMPLETA = c(2.614756053, -0.024301277, -0.024301277 ), PIE2013_T4_COMP = c(2.653056483, 0.013999154, 0.013999154), PIE2013_T5_COMPL = c(1.861263144, -0.084647005, -0.084647005 ), PIE2014_COMP = c(2.304771706, 1.005488722, -0.093123567 ), PIE2016_T0_COMPLETA = c(-0.141271428, -0.141271428, -0.141271428 ), PIE2016_T1_COMPLETA = c(-0.081696055, -0.081696055, -0.081696055 ), PIE2016_T3 = c(-0.019385468, -0.019385468, -0.019385468 ), PIE2016_T3_TOR = c(0.045856809, 0.045856809, 0.045856809 ), PIE2017_T0_COMPLETA = c(4.493506636, 0.189441543, 0.189441543 ), PIE2017_T1_COMPLETA = c(5.001671041, 0.71808448, 0.024937299 ), PIE2017_T2_TOR = c(5.887191114, 0.672255357, -0.020891824 ), PIE2017_T3 = c(3.306066839, 0.703377154, 0.010229973), PIE2017_T4_COMP = c(5.560847286, 1.371192544, -0.015101817 ), PIE2017_T5_COMPL = c(5.688626959, -0.025105846, -0.025105846 ), PIE2018_T1 = c(0.158551089, 0.158551089, 0.158551089), PIE2019_T1_COMPL = c(6.659430141, 0.833430034, 0.140282853 )), row.names = c(NA, 3L), class = "data.frame")
解决方案(更新后的脚本)
# 将最后39列的T0替换为T6,标记为对照组 colnames(df)[363:401] <- gsub("T0", "T6", colnames(df)[363:401]) df %>% # 宽表转长表,保留细菌种类列,其余样本列转为名称-数值对 pivot_longer(-Bacteria) %>% # 从样本名称中提取分组前缀和时间点 mutate(group = gsub('_.*$', '', name), time = gsub('^.*_(T\\d+).*$', '\\1', name)) %>% # 过滤出包含时间标记(T+数字)的有效行 filter(grepl('T\\d+', time)) %>% # 构建绘图对象 ggplot(aes(time, value, fill = Bacteria)) + # 绘制均值柱状图,不同细菌并列展示 geom_bar(stat = 'summary', fun = 'mean', position = 'dodge') + # 添加均值标准误误差线,与柱状图对齐 stat_summary(fun.data = "mean_se", geom = "errorbar", width = 0.2, position = position_dodge(0.9)) + # 使用极简主题 theme_minimal() + # 按细菌种类纵向分面,每个细菌单独一张图,Y轴自由缩放适配数据范围 facet_grid(Bacteria ~ ., scale = 'free_y') + # 设置填充色为Set1调色板 scale_fill_brewer(palette = 'Set1') + # 添加面板边框,提升可读性 theme(panel.border = element_rect(fill = NA, color = 'gray75'))
绘图结果

内容的提问来源于stack exchange,提问作者WindSur
相关产品推荐
相关产品推荐

