1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
| library(Matrix) library(Seurat) library(plyr) library(dplyr) library(patchwork) library(purrr)
library(RColorBrewer) library(ggplot2) library(ggrepel) blank_theme <- theme_minimal()+ theme( axis.title.x = element_blank(), axis.text.x=element_blank(), axis.title.y = element_blank(), axis.text.y=element_blank(), panel.border = element_blank(), panel.grid=element_blank(), axis.ticks = element_blank(), plot.title=element_text(size=14, face="bold",hjust = 0.5) ) col_Paired <- colorRampPalette(brewer.pal(12, "Paired")) f_pie <- function(lc_x, lc_main, lc_x_p = 1.3, lc_r = T){ lc_cols <- col_Paired(length(lc_x)) lc_v <- as.vector(100*lc_x) lc_df <- data.frame(type = names(lc_x), nums = lc_v) lc_df <- lc_df[order(lc_df$type),] lc_percent = sprintf('%0.2f%%',lc_df$nums) if(lc_r){ lc_df$pos <- with(lc_df, 100-cumsum(nums)+nums/2) }else{ lc_df$pos <- with(lc_df, cumsum(nums)-nums/2) } lc_pie <- ggplot(data = lc_df, mapping = aes(x = 1, y = nums, fill = type)) + geom_bar(stat = 'identity') # print(lc_df) # print(lc_pie) lc_pie <- lc_pie + coord_polar("y", start=0, direction = 1) + scale_fill_manual(values=lc_cols) + blank_theme lc_pie <- lc_pie + geom_text_repel(aes(x = lc_x_p, y=pos),label= lc_percent, force = T, arrow = arrow(length=unit(0.01, "npc")), segment.color = "#cccccc", segment.size = 0.5) lc_pie <- lc_pie + labs(title = lc_main) lc_pie }
f_pie_metaN <- function(sObject, lc_group.by){ tp_data <- prop.table(table(sObject[[lc_group.by]])) f_pie(tp_data, sprintf('Proportion of %s', lc_group.by)) }
f_UMAP_more <- function(sObject, lc_group.by, lc_reduction="umap"){ res <- (DimPlot(sObject, reduction = lc_reduction, group.by = lc_group.by[1], label = T, repel = T, label.size = 6) + labs(title = lc_group.by[1])) for(lc_i in 2:length(lc_group.by)){ res <- res/ (DimPlot(sObject, reduction = lc_reduction, group.by = lc_group.by[lc_i], label = T, repel = T, label.size = 6) + labs(title = lc_group.by[lc_i])) } res }
f_br_cluster_f <- function(sObject, lc_groupN){ lc_filter <- unlist(unique(sObject[[lc_groupN]])) lc_filter <- lc_filter[!is.na(lc_filter)] lc_filter }
f_br_cluster <- function(sObject, lc_groupN, lc_labelN, lc_prop = F){ lc_all <- unique(sObject[[lc_labelN]]) rownames(lc_all) <- lc_all[[1]] colnames(lc_all) <- "CB" lc_tp <- SplitObject(subset(x = sObject, !!sym(lc_groupN)%in%f_br_cluster_f(sObject, lc_groupN)), split.by = lc_groupN) for(lc_i in 1:length(lc_tp)){ if(lc_prop){ lc_tp[[lc_i]] <- prop.table(table(lc_tp[[lc_i]][[lc_labelN]])) }else{ lc_tp[[lc_i]] <- table(lc_tp[[lc_i]][[lc_labelN]]) } } for(lc_name in names(lc_tp)){ lc_all[[lc_name]] = 0 lc_all[names(lc_tp[[lc_name]]), lc_name] = lc_tp[[lc_name]] } lc_all[,-1] } f_q2l <- function(lc_q){ res <- NULL for(lc_c in colnames(lc_q)){ for(lc_r in rownames(lc_q)){ res <- rbind(res, c(group=lc_c, label=lc_r, value=lc_q[lc_r,lc_c])) } } res <- data.frame(res) res$value = as.numeric(res$value) res } library(RColorBrewer) library(ggplot2) col_Paired <- colorRampPalette(brewer.pal(12, "Paired")) f_q_frequnency <- function(lc_q){ ggplot(f_q2l(lc_q),mapping = aes(group,value,fill=label))+ geom_bar(stat='identity',position='fill') + scale_fill_manual(values= col_Paired(nrow(lc_q)))+ labs(x = 'group',y = 'frequnency') + theme(axis.title =element_text(size = 16),axis.text =element_text(size = 14, color = 'black'))+ theme(axis.text.x = element_text(angle = 45, hjust = 1))+coord_flip() }
f_DEG_Volcano <- function(lc_logFC, lc_p, lc_gene, Threshold_logFC = 1, Threshold_p = 0.05, lc_rep=1:10){ col_vector = rep(rgb(108, 200, 228, maxColorValue = 255), length(lc_logFC)) col_vector[lc_p < Threshold_p & lc_logFC > Threshold_logFC] = rgb(226, 61, 75, maxColorValue = 255) col_vector[lc_p < Threshold_p & lc_logFC < -Threshold_logFC] = rgb(232, 168, 71, maxColorValue = 255) lc_p[lc_p < 1e-10] = 1e-10 lc_p[lc_p > 1 is.na(lc_p)] = 1 df = data.frame(logFC <- lc_logFC, `-log10(P)` <- -log10(lc_p), col <- col_vector, gene <- lc_gene) colnames(df) <- c('logFC', '-log10(P)', "col", "gene") lc_tp_logFC <- df$logFC lc_tp_logFC[lc_p>=Threshold_p] = 0 lc_idx <- order(lc_tp_logFC)[c(lc_rep, length(lc_gene)+1-lc_rep)] df$logFC[df$logFC > 10] = 10 df$logFC[df$logFC < -10] = -10 res <- ggplot() + geom_point(aes(logFC, `-log10(P)`, col=I(col)), data = df) res <- res + theme_bw() + theme(panel.grid=element_line(colour=NA)) res <- res + geom_hline(yintercept=-log10(Threshold_p), linetype="longdash") res <- res + geom_vline(xintercept=c(Threshold_logFC, -Threshold_logFC), linetype="longdash") res <- res + geom_text_repel(data=df[lc_idx,],aes(logFC,`-log10(P)`,label=gene), force=T, max.overlaps=Inf) res }
f_cluster_averages <- function(lc_scRNA, lc_metaN='ident'){ # 切分出Clusters lc_clusters <- SplitObject(lc_scRNA, split.by = lc_metaN) for (lc_i in 1:length(lc_clusters)){ lc_clusters[[lc_i]] <- lc_clusters[[lc_i]][[lc_clusters[[lc_i]]@active.assay]]@scale.data } for (lc_i in 1:length(lc_clusters)){ lc_clusters[[lc_i]] <- apply(lc_clusters[[lc_i]],1,mean) } lc_clusters <- data.frame(lc_clusters) scale(lc_clusters) } library(clusterProfiler) library(pheatmap) library(ggdendro) f_DEG_hclust <- function(lc_counts){ ggdendrogram(hclust(dist(t(lc_counts))), rotate = T, size = 3)+theme(axis.text = element_text(size=14,face = "bold")) }
f_DEG_pheatmap_choose_matrix <- function(lc_tp_d, lc_significant_markers, lc_n = 120, Threshold_logFC = 1){ res <- subset(lc_significant_markers, abs(avg_log2FC) > Threshold_logFC) res <- res[order(abs(res$avg_log2FC), decreasing = T),] res <- head(unique(res$gene), n = lc_n) res <- lc_tp_d[res,] res }
require(ggplotify) f_DEG_pheatmap <- function(choose_matrix){ choose_matrix = t(scale(t(choose_matrix))) as.ggplot(pheatmap(choose_matrix)) }
f_prepare4CSOmap <- function(lc_scRNA, lc_csomap_data_dir, lc_className){ lc_csomap_data_dir <- system(paste("echo", lc_csomap_data_dir), intern = T) if(!file.exists(lc_csomap_data_dir)){dir.create(lc_csomap_data_dir)} # 导出label.txt labels <- lc_scRNA[[lc_className]] labels$cells <- gsub("-", "." ,rownames(labels)) # TPM的colnames 不知为何导出时被替换了,这里也替换一下 labels$labels <- as.character(labels[[lc_className]]) rownames(labels) <- NULL labels = labels[,c("cells", "labels")] write.table(labels, file.path(lc_csomap_data_dir, "label.txt"), row.names = F, sep = "\t", quote = F) # 不要引号 # copy LR_pairs.txt file.copy(from = file.path(lc_csomap_data_dir,"..","demo","LR_pairs.txt"), to = file.path(lc_csomap_data_dir, "LR_pairs.txt")) # 导出TPM.txt tpm <- exp(lc_scRNA[['RNA']]@data) tpm <- tpm - 1 tpm <- tpm*100 # 1E4 to 1E6 colnames(tpm)[1] = paste0('T', colnames(tpm)[1]) # 预留\t位置 write.table(tpm, file.path(lc_csomap_data_dir, "TPM.txt"), sep = "\t", quote = F) # 不要引号 lc_fix <- tempfile() lc_py <- sprintf(' import mmap, os def mapfile(filename, *args, size=None, **kwargs): file = open(filename, *args, **kwargs) if size is None: size = os.path.getsize(filename) return mmap.mmap(file.fileno(), size) path = "%s" print(path, "%s") f = mapfile(path,"r+", size=10) f[0:1] = b"\t" print(f[:]) f.close() print("Done") ', file.path(lc_csomap_data_dir, "TPM.txt"), lc_fix) print(lc_py) cat(file=lc_fix, lc_py) print(system(paste("python3", lc_fix), intern = T)) }
f_prepare4cellphoneDB <- function(lc_scRNA, lc_dir, lc_className){ if (!file.exists(lc_dir)){dir.create(lc_dir)} # 生成 count.txt write.table(as.matrix(lc_scRNA@assays$RNA@data), file.path(lc_dir,'cellphonedb_count.txt'), sep='\t', quote=F) # 生成 meta.txt lc_meta_data <- cbind(rownames(lc_scRNA@meta.data), lc_scRNA@meta.data[, lc_className, drop=F]) lc_meta_data <- as.matrix(lc_meta_data) lc_meta_data[is.na(lc_meta_data)] = "Unkown" # 细胞类型中不能有NA write.table(lc_meta_data, file.path(lc_dir,'cellphonedb_meta.txt'), sep='\t', quote=F, row.names=F) }
f_image_output <- function(fileName, image, width=1920, height=1080, lc_pdf=T, lc_resolution=72){ if(lc_pdf){ width = width / lc_resolution height = height / lc_resolution pdf(paste(fileName, ".pdf", sep=""), width = width, height = height) }else{ png(paste(fileName, ".png", sep=""), width = width, height = height) } print(image) dev.off() } # Rearrange data column sequence library(dplyr) f_cDB_order_sequence <- function(lc_df){ da <- data.frame() df <- subset(lc_df, receptor_a == 'True' & receptor_b == 'False' receptor_a == 'False' & receptor_b == 'True') for(i in 1:length(df$gene_a)){ sub_data <- df[i, ] if(sub_data$receptor_b=='False'){ if(sub_data$receptor_a=='True'){ old_names <- colnames(sub_data) my_list <- strsplit(old_names[-c(1:11)], split="\\") my_character <- paste(sapply(my_list, '[[', 2L), sapply(my_list, '[[', 1L), sep='') new_names <- c(names(sub_data)[1:4], 'gene_b', 'gene_a', 'secreted', 'receptor_b', 'receptor_a', "annotation_strategy", "is_integrin", my_character) sub_data = dplyr::select(sub_data, new_names) # print('Change sequence!!!') names(sub_data) <- old_names da = rbind(da, sub_data) } }else{ da = rbind(da, sub_data) } } return(da) } f_cDB_mergePandM <- function(means_order, pvals_order){ means_sub <- means_order[, c('interacting_pair', colnames(means_order)[-c(1:11)])] pvals_sub <- pvals_order[, c('interacting_pair', colnames(means_order)[-c(1:11)])] means_gather <- tidyr::gather(means_sub, celltype, mean_expression, names(means_sub)[-1]) pvals_gather <- tidyr::gather(pvals_sub, celltype, pval, names(pvals_sub)[-1]) mean_pval <- dplyr::left_join(means_gather, pvals_gather, by = c('interacting_pair', 'celltype')) mean_pval } f_readcellphoneDB <- function(lc_dir){ res = list() res$pvals <- f_cDB_order_sequence(read.delim(file.path(lc_dir, "out","pvalues.txt"), check.names = FALSE)) res$means <- f_cDB_order_sequence(read.delim(file.path(lc_dir, "out", "means.txt"), check.names = FALSE)) res$s_means <- read.delim(file.path(lc_dir, "out", "significant_means.txt"), check.names = FALSE) res$m_p <- f_cDB_mergePandM(res$means, res$pvals) lc_tp <- res$m_p %>% dplyr::select(interacting_pair, celltype, pval) %>% tidyr::spread(key=celltype, value=pval) lc_sig_pairs <- lc_tp[which(rowSums(lc_tp<=0.05)!=0), ] res$s_m_p <- subset(res$m_p, interacting_pair %in% lc_sig_pairs$interacting_pair) res } f_cDB_dotplot <- function(lc_m_p){ lc_m_p %>% ggplot(aes(x=interacting_pair, y=celltype)) + # geom_point(aes(color=log2(mean_expression), size=pval)) + # scale_size(trans = 'reverse') + geom_point(aes(color=log2(mean_expression), size=-log10(pval+1*10^-3)) ) + guides(colour = guide_colourbar(order = 1),size = guide_legend(order = 2)) + labs(x='', y='') + scale_color_gradientn(name='Expression level \n(log2 mean expression \nmolecule1, molecule2)', colours = terrain.colors(100)) + # scale_color_gradient2('Expression level \n(log2 mean expression \nmolecule1, molecule2)', low = 'blue', mid = 'yellow', high = 'red') + theme(axis.text.x= element_text(angle=45, hjust=1)) + # coord_flip() + theme( panel.border = element_rect(color = 'black', fill = NA), panel.grid.major.x = element_blank(), panel.grid.major.y = element_blank(), panel.grid.minor.x = element_blank(), panel.grid.minor.y = element_blank(), panel.background = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank(), axis.ticks = element_blank() # plot.title = element_text(hjust = 0.5), # legend.position = 'bottom' # guides(fill = guide_legend(label.position = "bottom")) # legend.position = "bottom" # axis.text.y.right = element_text(angle=270, hjust=0.5) ) + theme(legend.key.size = unit(0.4, 'cm'), #change legend key size # legend.key.height = unit(1, 'cm'), #change legend key height # legend.key.width = unit(1, 'cm'), #change legend key width legend.title = element_text(size=9), #change legend title font size legend.text = element_text(size=8)) #change legend text font size }
|