加載所需包
library(Seurat)
library(ggplot2)
library(ggsignif)
加載函數(shù)
- res:分辨率越高density的單位面積越小坝橡,根據(jù)細胞數(shù)目取值從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)
#提取單位區(qū)域的細胞
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)
}
加載數(shù)據(jù)
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)