R:箱线图

发布时间 2023-12-29 17:53:18作者: 王哲MGG_AI

两组对比,t.test计算差异

rm (list = ls ()) #清除所有变量
library(ggplot2)
library(ggpubr)
setwd("C:\\Users\\Administrator\\Desktop\\新建文件夹") #设置工作目录
index <- read.table('group.txt', header = TRUE, row.names = 1)
my_comparisons = list( c("B73", "Mo17") )
# 绘制箱线图并美化
p <- ggboxplot(index, x = "Group", y = "Shannon", color = "Group", add = "jitter") +
  stat_compare_means(comparisons = my_comparisons, method = "t.test", label = "p.signif") +
  theme_minimal(base_size = 14) +  # 使用简洁主题,调整基础字体大小
  labs(title = "Comparison of Shannon Diversity", 
       x = "Group", 
       y = "Shannon Index") +  # 添加标题和坐标轴标签
  theme(legend.position = "top",  # 将图例放置在顶部
        panel.grid.major = element_blank(),  # 去掉主要网格线
        panel.grid.minor = element_blank(),  # 去掉次要网格线
        panel.border = element_blank(),  # 去掉面板边框
        axis.line = element_line(colour = "black")) +  # 显示坐标轴的线
  scale_color_manual(values = c("B73" = "#8FC9E2", "Mo17" = "#ECC97F"))  # 自定义颜色

# 显示图形
print(p)
# 保存图形为PNG文件
ggsave("boxplot_shannon_diversity.png", plot = p, width = 10, height = 8, dpi = 600, bg = "white")

多组对比,AVNOA计算差异

rm (list = ls ()) #清除所有变量
library(ggplot2)
library(ggpubr)
setwd("C:\\Users\\Administrator\\Desktop\\新建文件夹") #设置工作目录
index <- read.table('group.txt', header = TRUE, row.names = 1)
# 进行ANOVA分析并进行Tukey多重比较
anova_result <- aov(Simpson ~ Group, data = index)
tukey_result <- TukeyHSD(anova_result)
print(summary(anova_result))
print(tukey_result)
# 手动设置基于Tukey多重比较结果的标签
# 注意:需要根据实际的Tukey测试结果来手动设置这些标签
group_labels <- data.frame(
  Group = c("Mo17_DAS28", "Mo17_DAS42", "Mo17_DAS56", "Mo17_DAS70"),
  label = c("a", "a", "a", "b")  # 所有组别都标记为"a"
)

# 绘制箱线图并美化
p <- ggboxplot(index, x = "Group", y = "Simpson", color = "Group", add = "jitter") +
  theme_minimal(base_size = 14) +
  labs(title = "Comparison of Simpson Diversity", x = "Group", y = "Simpson Index") +
  theme(legend.position = "top",
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        axis.line = element_line(colour = "black")) +
  scale_color_manual(values = c("Mo17_DAS28" = "#9BC985", "Mo17_DAS42" = "#F7D58B", "Mo17_DAS56" = "#B595BF", "Mo17_DAS70" = "#797BB7")) +
  geom_text(data = group_labels, aes(x = Group, y = max(index$Simpson) * 1.05, label = label), vjust = 0)  # 添加Tukey标签

# 显示图形
print(p)

# 保存图形为PNG文件
ggsave("boxplot_Simpson_diversity.png", plot = p, width = 10, height = 8, dpi = 600, bg = "white")