df <- read_tsv(paste0("figures/deg/",x))
name <- paste0(x)
deg_df <- df |> 
   filter(p_val_adj < 0.05)  |>
   mutate(change=ifelse(avg_log2FC>0,"up","down")) |>
   mutate(SYMBOL=symbol)
entrez_id <- bitr(deg_df$symbol, fromType = "SYMBOL",
               toType = c("ENTREZID"),
               OrgDb = org.Hs.eg.db) |>
               inner_join(deg_df,by="SYMBOL") 


parse_ratio <- function(ratio) {
   gsize <- as.numeric(sub("/\\d+$", "", as.character(ratio)))
   gcsize <- as.numeric(sub("^\\d+/", "", as.character(ratio)))
   return(gsize/gcsize)
}
options(digits = 2)
n = 10
entrez_id$change = str_to_lower(entrez_id$change)
kegg_up <- clusterProfiler::enrichKEGG(gene =entrez_id$ENTREZID[entrez_id$change=="up"],organism = 'hsa',pAdjustMethod="BH", use_internal_data =T)
kegg_down <- clusterProfiler::enrichKEGG(gene =entrez_id$ENTREZID[entrez_id$change=="down"],organism = 'hsa',pAdjustMethod="BH", use_internal_data =T)

kegg_up@result = mutate(kegg_up@result,change = "up")
kegg_down@result = mutate(kegg_down@result,change = "down")

kk = rbind(kegg_down@result[1:n,],kegg_up@result[1:n,])
kk$pvalue = ifelse(kk$change == "up",-log10(kk$pvalue),log10(kk$pvalue))

kk$ratio <- parse_ratio(kk$GeneRatio)
kk$ratio = ifelse(kk$change == "down",-kk$ratio,kk$ratio)


# default_labeller <- function(n) {
#     function(str){
#         str <- gsub("_", " ", str)
#         # yulab.utils::str_wrap(str, n)
#         str_wrap(str, n)
#     }
# }

kk$Description <- str_wrap(kk$Description, 40)

ggplot(kk,aes(reorder(Description, ratio),ratio,fill=change))+
 geom_col()+
 theme_bw()+
 theme(panel.grid.major=element_blank(),
       panel.grid.minor=element_blank(),
       panel.border = element_blank(),
       legend.title = element_blank(),
       axis.text = element_text(color="black",size=10),
       axis.line.x = element_line(color='black'),
       axis.ticks.y = element_blank(),
       axis.text.y = element_blank(),
       legend.position = 'none')+
 coord_flip()+
#   geom_segment(aes(y=0, yend=0,x=0,xend=18.5))+
 geom_text(data = kk[which(kk$ratio>0),],aes(x=Description, y=-0.01, label=Description),
           hjust=1, size=4)+
 geom_text(data = kk[which(kk$ratio<0),],aes(x=Description, y=0.01, label=Description),
           hjust=0, size=4)+
 geom_text(data = kk[which(kk$ratio>0),],aes(label=format(p.adjust, scientific = T)),
           hjust=-0.1, size=4, color='red')+
 geom_text(data = kk[which(kk$ratio<0),],aes(label=format(p.adjust, scientific = T)),
           hjust=1.1, size=4, color="red")+
 scale_fill_manual(values = c("#1084A4",
                              "#8D4873"))+
 scale_x_discrete(expand = expansion(mult = c(0,0)))+
 # ylim(-0., 0.5)+
 ylim(-max(abs(kk$ratio))-0.03, max(abs(kk$ratio))+0.03)+
 labs(x='', y='Ratio')


ggsave(file=paste0("enrichment/",x,".pdf"),width = 200,height =230,units = "mm")