library("clusterProfiler")
library("org.Hs.eg.db")  
library("enrichplot")
library("ggplot2")
library("colorspace")  # 用于更高级的颜色渐变
 
# 设置筛选阈值
pvalueFilter <- 0.05
qvalueFilter <- 0.05
 
# 设置颜色依据为 qvalue
colorSel <- "qvalue"
 
# 设置颜色渐变：蓝 -> 红 
colorGradient <- rev(sequential_hcl(100, h = c(260, 0), c = 100, l = c(30, 90)))  # 红蓝渐变
 
# 设置工作目录
setwd("F:\\血栓\\3.GO和KEGG富集分析\\GO富集分析")
 
# 读取输入文件
rt <- read.table("Genes.txt",  header = FALSE, sep = "\t", check.names  = FALSE)
 
# 获取差异基因列表并转换为 Entrez ID 
genes <- unique(as.vector(rt[,  1]))
entrezIDs <- mget(genes, org.Hs.egSYMBOL2EG,  ifnotfound = NA)
entrezIDs <- as.character(entrezIDs) 
gene <- entrezIDs[entrezIDs != "NA"]
 
# GO 富集分析（保留所有结果，用于绘图）
kk <- enrichGO(gene = gene,
               OrgDb = org.Hs.eg.db,  
               pvalueCutoff = 1,
               qvalueCutoff = 1,
               ont = "all",
               readable = TRUE)
 
# 将结果转换为数据框并进行筛选
GO <- as.data.frame(kk)  
GO <- GO[GO$pvalue < pvalueFilter & GO$qvalue < qvalueFilter, ]
 
# 保存富集结果
write.table(GO,  file = "GO.txt",  sep = "\t", quote = FALSE, row.names  = FALSE)
 
# 创建新的绘图值列，用于颜色映射
kk@result$plot_value <- ifelse(is.na(kk@result[[colorSel]]),  Inf, kk@result[[colorSel]])
 
# 设置通用颜色渐变范围 
colorLimits <- c(0, max(kk@result$plot_value[kk@result$plot_value != Inf], na.rm  = TRUE))
 
# 绘图1：柱状图（barplot）----------------------------------------------------
 
pdf(file = "柱状图.pdf", width = 9, height = 7)
 
bar <- barplot(kk, drop = TRUE, showCategory = 10, label_format = 130, split = "ONTOLOGY") + 
  facet_grid(ONTOLOGY ~ ., scale = 'free') +
  scale_fill_gradientn(
    colours = colorGradient,
    na.value  = "grey",
    limits = colorLimits
  ) +
  theme(
    axis.text.x  = element_text(angle = 45, hjust = 1),
    plot.title  = element_text(size = 14, face = "bold")
  ) +
  labs(title = "GO Enrichment Analysis", fill = "qvalue")
 
print(bar)
dev.off() 
 
# 绘图2：气泡图（dotplot）----------------------------------------------------
 
pdf(file = "bubble.pdf",  width = 9, height = 7)
 
bub <- dotplot(kk, showCategory = 10, orderBy = "GeneRatio", label_format = 130, split = "ONTOLOGY") + 
  facet_grid(ONTOLOGY ~ ., scale = 'free') +
  scale_color_gradientn(colours = colorGradient, limits = colorLimits) + 
  scale_fill_gradientn(colours = colorGradient, limits = colorLimits) +
  theme(
    axis.text.x  = element_text(angle = 45, hjust = 1),
    plot.title  = element_text(size = 14, face = "bold")
  ) +
  labs(title = "GO Enrichment Analysis", color = "qvalue", fill = "qvalue")
 
print(bub)
dev.off() 