挑选富集分析结果 enrichments

news2024/11/6 3:13:46


#2.2挑选term---

selected_clusterenrich=enrichmets[grepl(pattern = "cilium|matrix|excular|BMP|inflamm|development|muscle|
                                        vaso|pulmonary|alveoli",
                                        x = enrichmets$Description),]

head(selected_clusterenrich) 

distinct(selected_clusterenrich)

# remove duplicate rows based on Description 并且保留其他所有变量
distinct_df <- distinct(enrichmets, Description,.keep_all = TRUE)

library(ggplot2)
ggplot( distinct_df %>%
         dplyr::filter(stringr::str_detect(pattern = "cilium|matrix|excular|BMP|inflamm|development|muscle",Description))  %>%
         group_by(Description) %>%
         add_count()  %>%
         dplyr::arrange(dplyr::desc(n),dplyr::desc(Description)) %>%
         mutate(Description =forcats:: fct_inorder(Description))
       
       , #fibri|matrix|colla
       aes(Cluster, Description)) +
  geom_point(aes(fill=p.adjust, size=Count), shape=21)+
  theme_bw()+
  theme(axis.text.x=element_text(angle=90,hjust = 1,vjust=0.5),
        axis.text.y=element_text(size = 12),
        axis.text = element_text(color = 'black', size = 12)
  )+
  scale_fill_gradient(low="red",high="blue")+
  labs(x=NULL,y=NULL)
# coord_flip()

head(enrichmets)

ggplot( distinct(enrichmets,Description,.keep_all=TRUE)  %>% 
        #  dplyr::mutate(Cluster = factor(Cluster, levels = unique(.$Cluster))) %>%
           
          dplyr::mutate(Description = factor(Description, levels = unique(.$Description))) %>%
        #  dplyr::group_by(Cluster)  %>%
         dplyr::filter(stringr::str_detect(pattern = "cilium organization|motile cilium|cilium movemen|cilium assembly|
                                           cell-matrix adhesion|extracellular matrix organization|regulation of acute inflammatory response to antigenic stimulus|
                                           collagen-containing extracellular matrix|negative regulation of BMP signaling pathway|
                                           extracellular matrix structural constituent|extracellular matrix binding|fibroblast proliferation|
                                           collagen biosynthetic process|collagen trimer|fibrillar collagen trimer|inflammatory response to antigenic stimulus|
                                           chemokine activity|chemokine production|cell chemotaxis|chemoattractant activity|
                                           NLRP3 inflammasome complex assembly|inflammatory response to wounding|Wnt signaling pathway|response to oxidative stress|
                                           regulation of vascular associated smooth muscle cell proliferation|
                                           venous blood vessel development|regulation of developmental growth|lung alveolus development|myofibril assembly|
                                           blood vessel diameter maintenance|
                                           gas transport|cell maturation|regionalization|oxygen carrier activity|oxygen binding|
                                           vascular associated smooth muscle cell proliferation",Description))     %>%
       #  group_by(Description) %>%
         add_count()  %>%
         dplyr::arrange(dplyr::desc(n),dplyr::desc(Description))  %>%
        mutate(Description =forcats:: fct_inorder(Description))
       
       , #fibri|matrix|colla
       aes(Cluster, y = Description)) +  #stringr:: str_wrap
  geom_point(aes(fill=p.adjust, size=Count), shape=21)+
  theme_bw()+
  theme(axis.text.x=element_text(angle=90,hjust = 1,vjust=0.5),
        axis.text.y=element_text(size = 12),
        axis.text = element_text(color = 'black', size = 12)
  )+
  scale_fill_gradient(low="red",high="blue")+
  labs(x=NULL,y=NULL)
# coord_flip()
print(getwd())



p=ggplot( distinct(enrichmets,Description,.keep_all=TRUE)  %>%
            
            dplyr::mutate(Description = factor(Description, levels = unique(.$Description))) %>%  #调整terms显示顺序
            dplyr::filter(stringr::str_detect(pattern = "cilium organization|motile cilium|cilium movemen|cilium assembly|
                                           cell-matrix adhesion|extracellular matrix organization|regulation of acute inflammatory response to antigenic stimulus|
                                           collagen-containing extracellular matrix|negative regulation of BMP signaling pathway|
                                           extracellular matrix structural constituent|extracellular matrix binding|fibroblast proliferation|
                                           collagen biosynthetic process|collagen trimer|fibrillar collagen trimer|inflammatory response to antigenic stimulus|
                                           chemokine activity|chemokine production|cell chemotaxis|chemoattractant activity|
                                           NLRP3 inflammasome complex assembly|inflammatory response to wounding|Wnt signaling pathway|response to oxidative stress|
                                           regulation of vascular associated smooth muscle cell proliferation|
                                           venous blood vessel development|regulation of developmental growth|lung alveolus development|myofibril assembly|
                                           blood vessel diameter maintenance|
                                           gas transport|cell maturation|regionalization|oxygen carrier activity|oxygen binding|
                                           vascular associated smooth muscle cell proliferation",Description))  %>%
            group_by(Description) %>%
            add_count()  %>%
            dplyr::arrange(dplyr::desc(n),dplyr::desc(Description)) %>%
            mutate(Description =forcats:: fct_inorder(Description))
          
          , #fibri|matrix|colla
          aes(Cluster, y = Description)) +  #stringr:: str_wrap
  #scale_y_discrete(labels = function(x) stringr::str_wrap(x, width = 60)) +  #调整terms长度
  geom_point(aes(fill=p.adjust, size=Count), shape=21)+
  theme_bw()+
  theme(axis.text.x=element_text(angle=90,hjust = 1,vjust=0.5),
        axis.text.y=element_text(size = 12),
        axis.text = element_text(color = 'black', size = 12)
  )+
  scale_fill_gradient(low="red",high="blue")+
  labs(x=NULL,y=NULL)
# coord_flip()
print(getwd())




ggsave(filename ="~/silicosis/spatial/sp_cluster_rigions_after_harmony/enrichents12.pdf",plot = p,
       width = 10,height = 12,limitsize = FALSE)



######展示term内所有基因,用热图展示-------

#提取画图的数据
  
p$data


#提取图形中的所有基因-----
mygenes=  p$data $geneID %>% stringr::str_split(.,"/",simplify = TRUE)  %>%as.vector()   %>%unique()
frame_for_genes=p$data %>%as.data.frame() %>% dplyr::group_by(Cluster)  #后面使用split的话,必须按照分组排序
head(frame_for_genes)

my_genelist=  split(frame_for_genes, frame_for_genes$Cluster, drop = TRUE)  %>%  #注意drop参数的理解

  lapply(function(x) select(x, geneID));my_genelist
                  


my_genelist=  split(frame_for_genes, frame_for_genes$Cluster, drop = TRUE)  %>%  #注意drop参数的理解
  
  lapply(function(x) x$geneID);my_genelist

mygenes=my_genelist %>% lapply( function(x)  {stringr::str_split(x,"/",simplify = TRUE)  %>%as.vector()   %>%unique()}   )

#准备画热图,加载seurat对象
load("/home/data/t040413/silicosis/spatial_transcriptomics/silicosis_ST_harmony_SCT_r0.5.rds")
{dim(d.all)
  DefaultAssay(d.all)="Spatial"
  #visium_slides=SplitObject(object = d.all,split.by = "stim")
  
  names(d.all);dim(d.all)
  d.all@meta.data %>%head()
  head(colnames(d.all))
  #1 给d.all 添加meta信息------
  adata_obs=read.csv("~/silicosis/spatial/adata_obs.csv")
  head(adata_obs)
  mymeta=  paste0(d.all@meta.data$orig.ident,"_",colnames(d.all))  %>% gsub("-.*","",.)  # %>%  head()
  head(mymeta)
  tail(mymeta)
  
  #掉-及其之后内容
  adata_obs$col= adata_obs$spot_id %>% gsub("-.*","",.)    # %>%  head()
  head(adata_obs)
  
  rownames(adata_obs)=adata_obs$col
  adata_obs=adata_obs[mymeta,]
  head(adata_obs)
  identical(mymeta,adata_obs$col)
  d.all=AddMetaData(d.all,metadata = adata_obs)
  head(d.all@meta.data)}

##构建画热图对象---
Idents(d.all)=d.all$clusters
a=AverageExpression(d.all,return.seurat = TRUE)
a$orig.ident=rownames(a@meta.data)
head(a@meta.data)
head(markers)

rownames(a) %>%head()
head(mygenes)
table(mygenes %in% rownames(a))
DoHeatmap(a,draw.lines = FALSE, slot = 'scale.data', group.by = 'orig.ident',
          features = mygenes ) + 
  ggplot2:: scale_color_discrete(name = "Identity", labels =  unique(a$orig.ident) %>%sort()  )



##doheatmap做出来的图不好调整,换成heatmap自己调整

p=DoHeatmap(a,draw.lines = FALSE, slot = 'scale.data', group.by = 'orig.ident',
          features = mygenes ) + 
  ggplot2:: scale_color_discrete( labels =  unique(a$orig.ident) %>%sort()  ) #name = "Identity",

p$data %>%head()


##########这种方式容易出现bug,不建议------
if (F) {
  
    wide_data <- p$data %>% .[,-4] %>%
      tidyr:: pivot_wider(names_from = Cell, values_from = Expression)
    
    print(wide_data)  
    
    mydata=  wide_data %>%
      dplyr:: select(-Feature) %>%
      as.matrix()
    head(mydata)
    rownames(mydata)=wide_data$Feature
    mydata=mydata[,c("Bronchial zone", "Fibrogenic zone",   "Interstitial zone",  "Inflammatory zone","Vascular zone"  )]
    
    p2=pheatmap::  pheatmap(mydata, fontsize_row = 2, 
                            clustering_method = "ward.D2",
                            #     annotation_col = wide_data$Feature,
                            annotation_colors = c("Interstitial zone" = "red", "Bronchial zone" = "blue", "Fibrogenic zone" = "green", "Vascular zone" = "purple") ,
                            cluster_cols = FALSE,
                            column_order = c("Inflammatory zone", "Vascular zone"  ,"Bronchial zone", "Fibrogenic zone"   )
    )
    
    getwd()
    ggplot2::ggsave(filename = "~/silicosis/spatial/sp_cluster_rigions_after_harmony/heatmap_usingpheatmap.pdf",width = 8,height = 10,limitsize = FALSE,plot = p2)
    
    
   
}



##########建议如下方式画热图------
a$orig.ident=a@meta.data %>%rownames()
a@meta.data %>%head()
Idents(a)=a$orig.ident
 
a@assays$Spatial@scale.data  %>%head()

mydata=a@assays$Spatial@scale.data
mydata=mydata[rownames(mydata) %in% (mygenes %>%unlist() %>%unique()) ,]
mydata= mydata[,c( "Fibrogenic zone",  "Inflammatory zone",   "Bronchial zone","Interstitial zone","Vascular zone"  )]
head(mydata)
p3=pheatmap::  pheatmap(mydata, fontsize_row = 2,  
                    clustering_method = "ward.D2",
                    #     annotation_col = wide_data$Feature,
                    annotation_colors = c("Interstitial zone" = "red", "Bronchial zone" = "blue", "Fibrogenic zone" = "green", "Vascular zone" = "purple") ,
                    cluster_cols = FALSE,
                    column_order = c("Inflammatory zone", "Vascular zone"  ,"Bronchial zone", "Fibrogenic zone"   )
)

getwd()
ggplot2::ggsave(filename = "~/silicosis/spatial/sp_cluster_rigions_after_harmony/heatmap_usingpheatmap2.pdf",width = 8,height = 10,limitsize = FALSE,plot = p3)



#########单独画出炎症区和纤维化区---------
a@assays$Spatial@scale.data  %>%head()

mydata=a@assays$Spatial@scale.data
mygenes2= my_genelist[c('Inflammatory zone','Fibrogenic zone')] %>%  unlist() %>% stringr::str_split("/",simplify = TRUE) 

mydata2=mydata[rownames(mydata) %in% ( mygenes2 %>%unlist() %>%unique()) ,]
mydata2= mydata2[,c( "Fibrogenic zone",  "Inflammatory zone" )]
head(mydata2)

p3=pheatmap::  pheatmap(mydata2, fontsize_row = 5,  #scale = 'row',
                         clustering_method = "ward.D2",
                        #     annotation_col = wide_data$Feature,
                        annotation_colors = c("Interstitial zone" = "red", "Bronchial zone" = "blue", "Fibrogenic zone" = "green", "Vascular zone" = "purple") ,
                        cluster_cols = FALSE,
                        column_order = c("Inflammatory zone", "Vascular zone"  ,"Bronchial zone", "Fibrogenic zone"   )
)

getwd()
ggplot2::ggsave(filename = "~/silicosis/spatial/sp_cluster_rigions_after_harmony/heatmap_usingpheatmap3.pdf",width = 4,height = 8,limitsize = FALSE,plot = p3)




.libPaths(c("/home/data/t040413/R/x86_64-pc-linux-gnu-library/4.2",
            "/home/data/t040413/R/yll/usr/local/lib/R/site-library", 
            "/usr/local/lib/R/library",
            "/refdir/Rlib/"))

library(Seurat)
library(ggplot2)
library(dplyr)
load('/home/data/t040413/silicosis/fibroblast_myofibroblast2/subset_data_fibroblast_myofibroblast2.rds')



print(getwd())
dir.create("~/silicosis/fibroblast_myofibroblast2/slilica_fibroblast_enrichments")
setwd("~/silicosis/fibroblast_myofibroblast2/slilica_fibroblast_enrichments")
getwd()

DimPlot(subset_data,label = TRUE)

markers_foreach=FindAllMarkers(subset_data,only.pos = TRUE,densify = TRUE)
head(markers_foreach)



all_degs=markers_foreach
markers=markers_foreach

#install.packages("AnnotationDbi")
#BiocManager::install(version = '3.18')
#BiocManager::install('AnnotationDbi',version = '3.18')
{
  ##########################---------------------批量富集分析findallmarkers-enrichment analysis==================================================
  #https://mp.weixin.qq.com/s/WyT-7yKB9YKkZjjyraZdPg
  
  
  df=all_degs
  ##筛选阈值确定:p<0.05,|log2FC|>1
  p_val_adj = 0.05
  # avg_log2FC = 0.1
  
  fc=seq(0.8,1.4,0.2)
  print(getwd())
  #setwd("../")
  
  for (avg_log2FC in fc) {
    
  #  avg_log2FC=0.5
    
    dir.create(paste0(avg_log2FC,"/"))
    setwd(paste0(avg_log2FC,"/"))
    
    
    print(getwd())
    print(paste0("Start----",avg_log2FC))
    
    head(all_degs)
    #根据阈值添加上下调分组标签:
    df$direction <- case_when(
      df$avg_log2FC > avg_log2FC & df$p_val_adj < p_val_adj ~ "up",
      df$avg_log2FC < -avg_log2FC & df$p_val_adj < p_val_adj ~ "down",
      TRUE ~ 'none'
    )
    head(df)
    
    df=df[df$direction!="none",]
    head(df)
    dim(df)
    df$mygroup=paste(df$group,df$direction,sep = "_")
    head(df)
    dim(df)
    ##########################----------------------enrichment analysis=
    #https://mp.weixin.qq.com/s/WyT-7yKB9YKkZjjyraZdPg
    {
      library(clusterProfiler)
      library(org.Hs.eg.db) #人
      library(org.Mm.eg.db) #鼠
      library(ggplot2)
      # degs_for_nlung_vs_tlung$gene=rownames(degs_for_nlung_vs_tlung)
      head(markers)
      df=markers %>%dplyr::group_by(cluster)%>%
        filter(p_val_adj <0.05
        )
      sce.markers=df
      head(sce.markers)
      print(getwd())
      ids <- suppressWarnings(bitr(sce.markers$gene, 'SYMBOL', 'ENTREZID', 'org.Mm.eg.db'))
      head(ids)
      
      head(sce.markers)
      tail(sce.markers)
      dim(sce.markers)
      sce.markers=merge(sce.markers,ids,by.x='gene',by.y='SYMBOL')
      head(sce.markers)
      dim(sce.markers)
      sce.markers$group=sce.markers$cluster
      sce.markers=sce.markers[sce.markers$group!="none",]
      dim(sce.markers)
      head(sce.markers)
      getwd()
      #    sce.markers=openxlsx::read.xlsx("/home/data/t040413/silicosis/fibroblast_myofibroblast/group_enrichments/")
      #sce.markers$cluster=sce.markers$mygroup
      dim(sce.markers)
      head(sce.markers)
      gcSample=split(sce.markers$ENTREZID, sce.markers$cluster)
      
      library(clusterProfiler)
      gcSample # entrez id , compareCluster 
      print("===========开始go= All ont===========")
      xx <- compareCluster(gcSample, fun="enrichGO",OrgDb="org.Mm.eg.db" ,   #'org.Hs.eg.db',
                           pvalueCutoff=0.05) #organism="hsa",
      
      
      xx.BP <- compareCluster(gcSample, fun="enrichGO",OrgDb="org.Mm.eg.db" ,   #'org.Hs.eg.db',
                              pvalueCutoff=0.05,readable=TRUE,
                              ont="BP") #organism="hsa",
      p=clusterProfiler::dotplot(object = xx.BP,showCategory = 20,
                                 label_format =60) 
      p=p+ theme(axis.text.x = element_text(angle = 90, 
                                            vjust = 0.5, hjust=0.5))
      p
      ggsave(paste0(avg_log2FC,'_degs_compareCluster-BP_enrichment--3.pdf'),plot = p,width = 13,height = 40,limitsize = F)
      ggsave(paste0(avg_log2FC,'_degs_compareCluster-BP_enrichment--3.pdf'),plot = p,width = 13,height = 40,limitsize = F)
      
      xx.CC <- compareCluster(gcSample, fun="enrichGO",OrgDb="org.Mm.eg.db" ,   #'org.Hs.eg.db',
                              pvalueCutoff=0.05,readable=TRUE,
                              ont="CC") #organism="hsa",
      p=clusterProfiler::dotplot(object = xx.CC,showCategory = 20,
                                 label_format =60) 
      p=p+ theme(axis.text.x = element_text(angle = 90, 
                                            vjust = 0.5, hjust=0.5))
      p
      ggsave(paste0(avg_log2FC,'_degs_compareCluster-CC_enrichment--3.pdf'),plot = p,width = 13,height = 40,limitsize = F)
      ggsave(paste0(avg_log2FC,'_degs_compareCluster-CC_enrichment--3.pdf'),plot = p,width = 13,height = 40,limitsize = F)
      
      xx.MF <- compareCluster(gcSample, fun="enrichGO",OrgDb="org.Mm.eg.db" ,   #'org.Hs.eg.db',
                              pvalueCutoff=0.05,readable=TRUE,
                              ont="MF") #organism="hsa",
      p=clusterProfiler::dotplot(object = xx.MF,showCategory = 20,
                                 label_format =60) 
      p=p+ theme(axis.text.x = element_text(angle = 90, 
                                            vjust = 0.5, hjust=0.5))
      p
      ggsave(paste0(avg_log2FC,'_degs_compareCluster-MF_enrichment--3.pdf'),plot = p,width = 13,height = 40,limitsize = F)
      ggsave(paste0(avg_log2FC,'_degs_compareCluster-MF_enrichment--3.pdf'),plot = p,width = 13,height = 40,limitsize = F)
      
      
      
      print(getwd())
      
      .libPaths()
      
      
      print("===========开始 kegg All ont============")
      gg<-clusterProfiler::compareCluster(gcSample,fun = "enrichKEGG",  #readable=TRUE,
                                          keyType = 'kegg',  #KEGG 富集
                                          organism='mmu',#"rno",
                                          pvalueCutoff = 0.05 #指定 p 值阈值(可指定 1 以输出全部
      )
      
      p=clusterProfiler::dotplot(object = xx,showCategory = 20,
                                 label_format =100) 
      p=p+ theme(axis.text.x = element_text(angle = 90, 
                                            vjust = 0.5, hjust=0.5))
      p
      ggsave(paste0(avg_log2FC,'_degs_compareCluster-GO_enrichment--3.pdf'),plot = p,width = 13,height = 40,limitsize = F)
      ggsave(paste0(avg_log2FC,'_degs_compareCluster-GO_enrichment--3.pdf'),plot = p,width = 13,height = 40,limitsize = F)
      
      xx
      write.csv(xx,file = paste0(avg_log2FC,"compareCluster-GO_enrichment.csv"))
      
      p=clusterProfiler::dotplot(gg,showCategory = 20,
                                 label_format = 40) 
      p4=p+ theme(axis.text.x = element_text(angle = 90, 
                                             vjust = 0.5, hjust=0.5))
      p4
      print(paste("保存位置",getwd(),sep = "  :   "))
      ggsave(paste0(avg_log2FC,'_degs_compareCluster-KEGG_enrichment-2.pdf'),plot = p4,width = 13,height = 25,limitsize = F)
      ggsave(paste0(avg_log2FC,'_degs_compareCluster-KEGG_enrichment-2.pdf'),plot = p4,width = 13,height = 25,limitsize = F)
      
      gg
      openxlsx::write.xlsx(gg,file = paste0(avg_log2FC,"_compareCluster-KEGG_enrichment.xlsx"))
      
      getwd()
      openxlsx::write.xlsx(sce.markers,file = paste0(avg_log2FC,"_sce.markers_for_each_clusterfor_enrichment.xlsx"))
      
      
      ##放大图片
      {
        getwd()
        #bp
        p=clusterProfiler::dotplot(object = xx.BP,showCategory = 100,
                                   label_format =60) 
        p=p+ theme(axis.text.x = element_text(angle = 90, 
                                              vjust = 0.5, hjust=0.5))
        p
        ggsave(paste0(avg_log2FC,'_degs_compareCluster-BP_enrichment-100terms-3.pdf'),plot = p,width = 13,height = 100,limitsize = F)
        ggsave(paste0(avg_log2FC,'_degs_compareCluster-BP_enrichment-100terms-3.pdf'),plot = p,width = 13,height = 100,limitsize = F)
        print((getwd()))
        
        #cc
        p=clusterProfiler::dotplot(object = xx.CC,showCategory = 100,
                                   label_format =60) 
        p=p+ theme(axis.text.x = element_text(angle = 90, 
                                              vjust = 0.5, hjust=0.5))
        p
        ggsave(paste0(avg_log2FC,'_degs_compareCluster-CC_enrichment-100terms-3.pdf'),plot = p,width = 13,height = 100,limitsize = F)
        ggsave(paste0(avg_log2FC,'_degs_compareCluster-CC_enrichment-100terms-3.pdf'),plot = p,width = 13,height = 100,limitsize = F)
        print((getwd()))
        
        #MF
        p=clusterProfiler::dotplot(object = xx.MF,showCategory = 100,
                                   label_format =60) 
        p=p+ theme(axis.text.x = element_text(angle = 90, 
                                              vjust = 0.5, hjust=0.5))
        p
        ggsave(paste0(avg_log2FC,'_degs_compareCluster-MF_enrichment-100terms-3.pdf'),plot = p,width = 13,height = 100,limitsize = F)
        ggsave(paste0(avg_log2FC,'_degs_compareCluster-MF_enrichment-100terms-3.pdf'),plot = p,width = 13,height = 100,limitsize = F)
        print((getwd()))
        
        
        #KEGG
        p=clusterProfiler::dotplot(object = gg,showCategory = 100,
                                   label_format =60) 
        p=p+ theme(axis.text.x = element_text(angle = 90, 
                                              vjust = 0.5, hjust=0.5))
        p
        ggsave(paste0(avg_log2FC,'_degs_compareCluster-KEGG_enrichment-100terms-3.pdf'),plot = p,width = 13,height = 100,limitsize = F)
        ggsave(paste0(avg_log2FC,'_degs_compareCluster-KEGG_enrichment-100terms-3.pdf'),plot = p,width = 13,height = 100,limitsize = F)
        print((getwd()))
        
        
        
      }
      
      #   save(xx.BP,xx.CC,xx.MF, gg, file = "~/silicosis/spatial_transcriptomicsharmony_cluster_0.5res_gsea/xx.Rdata")
      
      xx.BP@compareClusterResult$oncology="BP"
      xx.CC@compareClusterResult$oncology="CC"
      xx.MF@compareClusterResult$oncology="MF"
      
      
      xx.all=do.call(rbind,list(xx.BP@compareClusterResult,
                                xx.CC@compareClusterResult,
                                xx.MF@compareClusterResult))
      head(xx.all)    
      openxlsx::write.xlsx(xx.all,file = paste0(avg_log2FC,"_enrichments_all.xlsx"))    
      
      # save(xx.BP,xx.CC,xx.MF,xx.all,sce.markers,merged_degs, gg, file = "./xx.Rdata")
      
      result <- tryCatch({
        save(xx.BP,xx.CC,xx.MF,xx.all,sce.markers,merged_degs, gg, file = paste0(avg_log2FC,"_xx.Rdata"))
        # 在这里添加你希望在没有报错时执行的代码
        print("没有报错")
      }, error = function(e) {
        print(getwd())  # 在报错时执行的代码
        
        # 在这里添加你希望在报错时执行的额外代码
        save(xx.BP,xx.CC,xx.MF,xx.all,sce.markers, gg, file = paste0(avg_log2FC,"_xx_all.Rdata"))
      })
      
      # print(result)
      
      
      
      
      print(getwd())
      if (F) { 
        #大鼠
        print("===========开始go============")
        xx <-clusterProfiler::compareCluster(gcSample, fun="enrichGO",OrgDb="org.Rn.eg.db",
                                             readable=TRUE,
                                             ont = 'ALL',  #GO Ontology,可选 BP、MF、CC,也可以指定 ALL 同时计算 3 者
                                             pvalueCutoff=0.05) #organism="hsa", #'org.Hs.eg.db',
        
        print("===========开始 kegg============")
        gg<-clusterProfiler::compareCluster(gcSample,fun = "enrichKEGG",
                                            keyType = 'kegg',  #KEGG 富集
                                            organism="rno",
                                            pvalueCutoff = 0.05 #指定 p 值阈值(可指定 1 以输出全部
        )
        
        p=dotplot(xx) 
        p2=p+ theme(axis.text.x = element_text(angle = 90, 
                                               vjust = 0.5, hjust=0.5))
        p2
        ggsave('degs_compareCluster-GO_enrichment-2.pdf',plot = p2,width = 6,height = 20,limitsize = F)
        xx
        openxlsx::write.xlsx(xx,file = "compareCluster-GO_enrichment.xlsx")
        #
        p=dotplot(gg) 
        p4=p+ theme(axis.text.x = element_text(angle = 90, 
                                               vjust = 0.5, hjust=0.5))
        p4
        print(paste("保存位置",getwd(),sep = "  :   "))
        ggsave('degs_compareCluster-KEGG_enrichment-2.pdf',plot = p4,width = 6,height = 12,limitsize = F)
        gg
        openxlsx::write.xlsx(gg,file = "compareCluster-KEGG_enrichment.xlsx")   
      }  
      
      setwd("../")
    }
    
  }
  
  
  
  
}

print(getwd())
#setwd('../')


load("~/silicosis/fibroblast_myofibroblast2/slilica_fibroblast_enrichments/1/1_xx_all.Rdata")




# remove duplicate rows based on Description 并且保留其他所有变量
xx.all<- distinct(xx.all, Description,.keep_all = TRUE)

enrichmets=xx.all

#2.2挑选term---

selected_clusterenrich=enrichmets[grepl(pattern = "lung alveolus developmen|extracellular matrix organization|extracellular structure organization|response to toxic substance|blood vessel endothelial cell migration
                                        regulation of blood vessel endothelial cell migration|lung development|respiratory tube development|detoxification|
                                        cellular response to toxic substance|endothelial cell proliferation|cellular response to chemical stress|
                                        Wnt|infla|fibrob|myeloid",
                                        x = enrichmets$Description) &
                                 stringr::str_detect(pattern = "muscle|fibroblast migration|positive regulation of endothelial cell proliferation|
                                                     inflammatory response to wounding|wound healing involved in inflammatory response|fibronectin binding|fibronectin binding|inflammatory response to wounding|fibronectin binding", negate = TRUE, string = enrichmets$Description)
                                    ,]

head(selected_clusterenrich) 

distinct(selected_clusterenrich)

# remove duplicate rows based on Description 并且保留其他所有变量
distinct_df <- distinct(selected_clusterenrich, Description,.keep_all = TRUE)

ggplot( distinct(selected_clusterenrich,Description,.keep_all=TRUE)  %>% 
          
          #  dplyr::mutate(Cluster = factor(Cluster, levels = unique(.$Cluster))) %>%
          
          dplyr::mutate(Description = factor(Description, levels = unique(.$Description))) %>%
          #  dplyr::group_by(Cluster)  %>%
         
          dplyr::filter(stringr::str_detect(pattern = "muscle", negate = TRUE,Description))  %>%
        
            add_count()  %>%
          dplyr::arrange(dplyr::desc(n),dplyr::desc(Description))  %>%
          mutate(Description =forcats:: fct_inorder(Description))
        
        , #fibri|matrix|colla
        aes(Cluster, y = Description)) +  #stringr:: str_wrap
  scale_y_discrete(labels = function(x) stringr::str_wrap(x, width = 58)) +  #调整terms长度 字符太长
  geom_point(aes(fill=p.adjust, size=Count), shape=21)+
  theme_bw()+
  theme(axis.text.x=element_text(angle=90,hjust = 1,vjust=0.5),
        axis.text.y=element_text(size = 12),
        axis.text = element_text(color = 'black', size = 12)
  )+
  scale_fill_gradient(low="red",high="blue")+
  labs(x=NULL,y=NULL)
# coord_flip()
print(getwd())




本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1378464.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

firewalld防火墙命令行工具

firewall-cmd命令 &#xff08;1&#xff09;启动、停止、查看firewalld服务 在安装CentOS 7系统时&#xff0c;会自动安装firewalld 和图形化工具firewall-config.执行以下命令可 以启动 firewalld 并设置为开机自启动状态。 [rootllcgc ~]# systemctl start firewalld.serv…

关于Python里xlwings库对Excel表格的操作(三十一)

这篇小笔记主要记录如何【如何使用“Chart类”、“Api类"和“Axes函数”设置绘图区外框线型、颜色、粗细及填充颜色】。前面的小笔记已整理成目录&#xff0c;可点链接去目录寻找所需更方便。 【目录部分内容如下】【点击此处可进入目录】 &#xff08;1&#xff09;如何安…

Unity中URP下实现能量罩(扭曲流光花纹)

文章目录 前言一、能量罩花纹1、在属性面板接收能量罩花纹纹理2、申明 纹理 和 采样器3、在顶点着色器,应用 Tilling 和 Offset4、在片元着色器,纹理采样后,与之前的结果相乘输出二、能量罩流光1、在顶点着色器,记录原uv值2、在片元着色器,使用 uv 的 y 值,乘以一个系数 …

Linux的DNS域名解析服务

一.DNS基础 1.1 DNS简介 DNS域名系统 &#xff08;Domain Name System 缩写为&#xff1a;DNS&#xff09;是因特网的一项核心服务&#xff0c;它作为可以将 域名 和 IP地址 相互映射的一个分布式数据库&#xff0c;能够使人更加方便的访问互联网&#xff0c;而不用去记住能够…

企业数据中台整体介绍及建设方案:文件全文51页,附下载

关键词&#xff1a;数据中台解决方案&#xff0c;数据治理&#xff0c;数据中台技术架构&#xff0c;数据中台建设内容&#xff0c;数据中台核心价值 一、什么是数据中台&#xff1f; 数据中台是指通过数据技术&#xff0c;对海量数据进行采集、计算、存储、加工&#xff0c;…

DNS域名解析以及操作流程

dns:将域名转化为IP地址的过程&#xff0c;域名方便人们记忆&#xff0c;ip地址过长&#xff0c;且都是数字&#xff0c;不方便记忆&#xff0c;所以才出现了域名。 怎么实现访问域名等于访问ip地址 1.老方法&#xff1a;写入文件里 /etc/hosts 左边 IP地址 右边域名 格式例…

XSS的利用(包含:蓝莲花、beef-xss)

0x00、环境搭建 dvwa靶场 操作指南和最佳实践:使用 DVWA 了解如何防止网站漏洞_dvwa源代码-CSDN博客 xss漏洞接收平台 下载:GitHub - firesunCN/BlueLotus_XSSReceiver 将解压后的BlueLotus_XSSReceiver原代码放置 phpstudy 安装目录的WWW文件夹下 访问平台:http://127…

N-137基于springboot,vue运动会报名管理系统

开发工具&#xff1a;IDEA 服务器&#xff1a;Tomcat9.0&#xff0c; jdk1.8 项目构建&#xff1a;maven 数据库&#xff1a;mysql5.7 系统分前后台&#xff0c;项目采用前后端分离 前端技术&#xff1a;vueAvueElementUI 服务端技术&#xff1a;springbootmybatis 本项…

XCTF:MISCall[WriteUP]

使用file命令&#xff0c;查看该文件类型 file d02f31b893164d56b7a8e5edb47d9be5 文件类型&#xff1a;bzip2 使用bzip2命令可对该文件进行解压 bzip2 -d d02f31b893164d56b7a8e5edb47d9be5 生成了一个后缀为.out的文件 再次使用file命令&#xff0c;查看该文件类型 file…

WARNING: IPv4 forwarding is disabled. Networking will not work.

今天用docker部署容器&#xff0c;发现一个问题&#xff0c;docker-compose up启动成功&#xff0c;但无法正常访问接口。 查找问题步骤&#xff1a; 1、直接在服务器运行jar包&#xff0c;发现可以正常启动&#xff0c;也能正常访问接口&#xff0c;排除jar包本身问题以及防…

Google推出Telecom Jetpack库,让Android通话应用创建更简单

Google推出Telecom Jetpack库&#xff0c;让Android通话应用创建更简单 Telecom Jetpack库的最新Alpha版本已经推出。该库提供了多个API&#xff0c;以简化Android开发者创建语音和/或视频通话应用程序的过程&#xff0c;支持常见功能&#xff0c;例如接听/拒绝、音频路由等等…

在机械行业中,直线导轨和弧形导轨哪个应用范围更广泛?

弧形导轨和直线导轨是两种常见的导轨类型&#xff0c;直线导轨主要被用于高精度或快速直线往复运动场所&#xff0c;而弧形导轨是一种专门设计用于曲线运动的导轨系统&#xff0c;那么在机械行业中&#xff0c;直线导轨和弧形导轨哪个应用范围更加广泛呢&#xff1f; 直线导轨主…

python如何安装numpy

1. 根据python版本下载相应版本的numpy保存至D:\Program Files (x86)\Python\Python37\Scripts\ numpy下载地址 2. winR&#xff0c;输入cmd&#xff0c;打开命令行窗口&#xff0c;定位到python的安装目录 3. 输入python -m pip install numpy或定位到目录&#xff1a;D:\P…

【STC8A8K64D4开发板】第2-9讲:比较器

学习目的学习比较器的作用和原理。掌握比较器的应用流程包括配置、启动以及中断服务函数的编写。 比较器原理 STC8A8K64D4单片机片内集成了比较器&#xff08;Comparator&#xff09;&#xff0c;比较器有两个输入端IN&#xff08;正端输入端&#xff09;和&#xff08;负端输…

代码随想录算法训练营第25天 | 216.组合总和III 17.电话号码的字母组合

目录 216.组合总和III &#x1f4a1;解题思路 回溯三部曲 &#x1f4bb;实现代码 17.电话号码的字母组合 &#x1f4a1;解题思路 # 数字和字母如何映射 # 回溯法来解决n个for循环的问题 &#x1f4bb;实现代码 216.组合总和III 题目链接&#xff1a;216.组合总和III …

深度学习笔记(四)——TF2构建基础网络常用函数+简单ML分类网络实现

文中程序以Tensorflow-2.6.0为例 部分概念包含笔者个人理解&#xff0c;如有遗漏或错误&#xff0c;欢迎评论或私信指正。 截图和程序部分引用自北京大学机器学习公开课 TF2基础常用函数 1、张量处理类 强制数据类型转换&#xff1a; a1 tf.constant([1,2,3], dtypetf.floa…

鸿蒙开发环境搭建-高频环境问题解决

1.Node版本问题 由于SDK的部分工具依赖Node.js运行时&#xff0c;推荐使用配套API版本的Node.js&#xff0c;保证工程的兼容性。 匹配关系见下表&#xff1a; API LevelNode.js支持范围API Level≤914.x&#xff08;≥14.19.1&#xff09;、16.xAPI Level>914.x&#xff0…

软件测试之项目立项与需求评审

&#x1f4e2;专注于分享软件测试干货内容&#xff0c;欢迎点赞 &#x1f44d; 收藏 ⭐留言 &#x1f4dd; 如有错误敬请指正&#xff01;&#x1f4e2;软件测试面试题分享&#xff1a; 1000道软件测试面试题及答案&#x1f4e2;软件测试实战项目分享&#xff1a; 纯接口项目-完…

ASP .net core微服务实战(杨中科)

背景&#xff1a; 主要是思考下&#xff0c;我们为什么要用微服务&#xff1f; 微服务我现在理解是&#xff1a;提供了我们一种模块化的手段&#xff0c;一个服务负责一种类型的业务&#xff0c;是一种面对复杂问题进行拆分的方式&#xff0c;但是也会引入一些中间件&#xf…

基于爬虫和Kettle的豆瓣电影的采集与预处理

一&#xff1a;爬虫 1、爬取的目标 将豆瓣电影网上的电影的基本信息&#xff0c;比如&#xff1a;电影名称、导演、电影类型、国家、上映年份、评分、评论人数爬取出来&#xff0c;并将爬取的结果放入csv文件中&#xff0c;方便存储。 2、网站结构 图1豆瓣网网站结构详…