加载所需包
library(Seurat)
library(ggplot2)
library(ggsignif)
加载函数
- res:分辨率越高density的单位面积越小,根据细胞数目取值从10-100
- type.1和type.2分别为sample_type的两个因子
- type.1的百分比为正,type.2的百分比为负
- filename:不包含后缀的文件名,输出pdf文件
PlotDensity <- function(seurat.object,res,type.1,type.2,filename,path.out){
sample_type <- seurat.object@meta.data$sample_type
names(sample_type) <- rownames(seurat.object@meta.data)
#提取坐标,也可以将umap改为tsne提取tsne的坐标
coord <- seurat.object@reductions$umap@cell.embeddings
r_x <- (max(coord[, 1])-min(coord[, 1]))/res #横坐标的单位距离
r_y <- (max(coord[, 2])-min(coord[, 2]))/res #纵坐标的单位距离
x_left <- apply(coord,1,function(x){x[1] - r_x})
x_right <- apply(coord,1,function(x){x[1] + r_x})
y_up <- apply(coord,1,function(x){x[2] + r_y})
y_down <- apply(coord,1,function(x){x[2] - r_y})
coord_span <- data.frame(left=x_left,right=x_right,up=y_up,down=y_down)
#提取单位区域的细胞
coord_span$cell <- rownames(coord_span)
coord_span_list <- split(coord_span,f=coord_span$cell)
cell_pool_list <- lapply(coord_span_list,function(span){
cell_pool <- rownames(coord)[apply(coord,1,function(x) {
ifelse(x[1] > span[1] & x[1] < span[2] & x[2] < span[3] & x[2] > span[4],TRUE,FALSE)
})]
})
#计算比例
final_percent <- lapply(cell_pool_list,function(x) {
n1 <- table(sample_type[match(x,names(sample_type))])[[type.1]]
n2 <- table(sample_type[match(x,names(sample_type))])[[type.2]]
percent_n1 <- n1/(n1+n2)
percent_n2 <- n2/(n1+n2)
percent <- ifelse(percent_n1 > percent_n2,percent_n1,-percent_n1) #crF为正,MAT为负
})
seurat.object[["density"]] <- unlist(final_percent)
plot <- FeaturePlot(seurat.object,features = "density",pt.size=1)+scale_color_gradient2(low='#003399',mid='white',high='#990000')
ggsave(paste0(filename,".pdf"),plot,path=path.out,width = 8, height = 5)
}
加载数据
path_out_BioRad_debach_FAP <- "/data/zhaoxueya/project/gut/result/BioRad/CD_merge/debach/subset/FAP"
seurat_object_FAT <- readRDS(file=paste(path_out_BioRad_debach_FAP,"seurat_object_subset.rds", sep="/"))
PlotDensity(seurat.object=seurat_object_FAT,res=10,type.1="CrF",type.2="MAT",filename="test10",path.out=path_out_BioRad_debach_FAP)