Seurat单细胞分析常见代码-01

1.如何通过Seurat对象获取细胞对应的坐标?

UMAP_coord <- data_obj@reductions$umap@cell.embeddings
TSNE_coord <- data_obj@reductions$tsne@cell.embeddings

pbmc_umap_coord <- data_obj@reductions$umap 
pbmc_umap_coord2 <- as.data.frame(pbmc_umap_coord)

2.如何通过Seurat对象获取原始表达数据?

DefaultAssay(data_obj) <- 'RNA' 
countdata <- GetAssayData(data_obj, slot = "counts") 
write.table(countdata,"./finial_result/raw_count_combine.txt")

# GetAssayData(data_obj, slot = "counts")等同于data_obj@assays$RNA@counts
GetAssayData(data_obj, slot = "counts")
data_obj@assays$RNA@counts

3.提取特定基因阳性表达的细胞?

# 单个基因
DefaultAssay(data_obj) <- "RNA"
gene_name <- "CD4"
names(which(data_obj@assays$RNA@counts[gene_name,]>0))
WhichCells(object = data_obj, expression = CD4 > 0, slot = "counts")

# 也可用FetchData()提取基因表达量
# for total co-positive cells:
Co_Positive <- function(object,gene1,gene2){
  CellData <- FetchData(object, vars = c(gene1,gene2), slot = "data")
  print(head(CellData))
  Gene1_total_cells <- sum(CellData[,gene1]>0)
  cat("Total cells positive for", gene1,Gene1_total_cells," ")
  Gene2_total_cells <- sum(CellData[,gene2]>0)
  cat("Total cells positive for", gene2,Gene2_total_cells)
  Co_Postitive_cell_ID <- subset(CellData, CellData[,gene1]>0)
  Co_Postitive_cell_ID <- subset(Co_Postitive_cell_ID, Co_Postitive_cell_ID[,gene2]>0)
  print(head(Co_Postitive_cell_ID))
  Co_Postitive_cell_Total <- nrow(Co_Postitive_cell_ID)
  cat("Total cells positive for",gene1," & ",gene2," ", Co_Postitive_cell_Total)
}

# 从总样本总细胞中提取出CD4 CXCR5 Foxp3三阳性的细胞
WhichCells(data_obj, slot = 'counts', expression = CD4 > 0 | CXCR5 > 0 | FOXP3 > 0)
How to subset using AND, working on raw counts as above. 
WhichCells(data_obj, slot = 'counts', expression = CD4 > 0 & CXCR5 > 0 & FOXP3 > 0)

# 提取细胞
select_cells <- WhichCells(data_obj, slot = 'counts', expression = CD4 > 0 & CXCR5 > 0 & FOXP3 > 0)
select_obj <- subset(data_obj, cells = select_cells)

4.修改tsne/umap图的配色

.cluster_cols <- c( 
  "#DC050C", "#FB8072", "#1965B0", "#7BAFDE", "#882E72", 
  "#B17BA6", "#FF7F00", "#FDB462", "#E7298A", "#E78AC3", 
  "#33A02C", "#B2DF8A", "#55A1B1", "#8DD3C7", "#A6761D", 
  "#E6AB02", "#7570B3", "#BEAED4", "#666666", "#999999", 
  "#aa8282", "#d4b7b7", "#8600bf", "#ba5ce3", "#808000", 
  "#aeae5c", "#1e90ff", "#00bfff", "#56ff0d", "#ffff00")

p1 <- DimPlot(data_obj, reduction = "umap",label=T,group.by = "cluster", 
               cols = colorRampPalette(.cluster_cols,space="rgb")(length(unique(ColonData$cluster)))) 
save_plot("DimPlot_UMAP_clustering.png", p1, base_height = 8, base_aspect_ratio = 1.3, base_width = NULL, dpi=600) 
save_plot("DimPlot_UMAP_clustering.pdf", p1, base_height = 8, base_aspect_ratio = 1.3, base_width = NULL)

5.查看tsne/umap图的默认配色

# 如celltype最后一个为Unkown,用灰色表示
library(scales) 
my_color_palette <- c(hue_pal()(3), "gray") 
Idents(data_obj) <- "celltype" 
p1 <- DimPlot(data_obj, reduction = "tsne", label = TRUE, label.size = 3, pt.size=0.1, raster=FALSE) + scale_color_manual(values = my_color_palette)+labs(title="")

6.加载R包

方式1:
使用suppressMessages运行的时候不显示提示信息

suppressMessages({ 
  library(Seurat) 
  library(cowplot) 
  library(ggplot2) 
  library(dplyr) 
  library(tidyverse) 
  library(RColorBrewer) 
  library(reshape2) 
})

方式2:
有的包在加载的时候会显示很多信息,可以使用 suppressPackageStartupMessages 函数来抑制这些信息的输出。

invisible(lapply(c("R.utils","Seurat","dplyr","kableExtra","ggplot2","scater", 
                   "scran","BiocSingular","Matrix","cowplot"), function(x) { 
                           suppressPackageStartupMessages(library(x,character.only = T)) 
                   }))

方式3:
easypackages能轻松加载多个R包

# Load libraries 
library(easypackages) 
packages <- c('clusterProfiler', 'org.Mm.eg.db', 'org.Hs.eg.db', 'GSEABase', 'biomaRt', 'enrichplot','plyr', 'dplyr', 'cowplot', 'ggplot2', 'patchwork') 
libraries(packages)

7.给cluster定义细胞类型

data_obj$celltype <- "NA" 
data_obj@meta.data[data_obj@meta.data$cluster %in% c("B0", "B2", "B6"),]$celltype <- "Naïve B" 
data_obj@meta.data[data_obj@meta.data$cluster %in% c("B1","B3","B4","B5"),]$celltype <- "Memory B" 
data_obj@meta.data[data_obj@meta.data$cluster %in% c("B7"),]$celltype <- "Plasma B" 
data_obj@meta.data[data_obj@meta.data$cluster %in% c("B8"),]$celltype <- "Unknown"

8.小鼠基因转成首字母大写

library(Hmisc) 
gene_list$Gene <- capitalize(tolower(gene_list$Gene))

9.统计不同resolution下的cluster数目分布

cluster_list <- sapply(grep("RNA_snn_res",sort(colnames(data_obj@meta.data)),value = TRUE),function(x) length(unique(data_obj@meta.data[,x]))) 
cluster_list <- as.data.frame(cluster_list) %>% tibble::rownames_to_column("resolution") 
colnames(cluster_list) <- c("resolution", "cluster_nums") 
write.csv(cluster_list, file = file.path(sample_analysis_path, "cluster_resolution_range_table.csv"), row.names = F)

10.可视化不同resolution下的umap图

DiffResolution_plot <- lapply(seq(0.05,0.3,by=0.05),function(i){ 
  p <- DimPlot(data_obj, reduction = "umap",label=T,group.by = paste("RNA_snn_res.",i,sep=""),cols = .cluster_cols)+ 
    labs(title=paste("Resolution = ",i,sep=""))+NoLegend() 
  return(p) 
}) 
p_res <- cowplot::plot_grid(plotlist = DiffResolution_plot,ncol=3) 
save_plot("Cluster_with_Different_resolution_UMAP.png", p_res, base_height = 12, base_aspect_ratio = NULL, base_width = 20, dpi=600) 
save_plot("Cluster_with_Different_resolution_UMAP.pdf", p_res, base_height = 12, base_aspect_ratio = NULL, base_width = 20)

11.指定resolution为当前cluster

Idents(data_obj) <- selected_resolution  
data_obj$cluster <- factor(Idents(data_obj), levels = sort(as.numeric(levels(Idents(data_obj)))))

12.统计每个样本的celltype占比

total_populations <- data_obj@meta.data %>% group_by(celltype) %>% summarize (total.pop = n()) 
# gets the proportion of cells for each cell type within a group by dividing by the total 
count_populations <- data_obj@meta.data %>% group_by_at(vars(orig.ident, "celltype")) %>% summarize (n = n()) 
count_populations <- left_join(count_populations, total_populations, by = "celltype") 
count_populations <- count_populations %>% mutate (proportion = n/total.pop) 
count_populations <- count_populations  %>% arrange(celltype, orig.ident)  
colnames(count_populations) <- c("sample", "celltype", "count", "total.pop", "proportion") 
write.csv(count_populations, "celltype_proportion_table.csv")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,793评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,567评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,342评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,825评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,814评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,680评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,033评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,687评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,175评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,668评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,775评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,419评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,020评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,206评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,092评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,510评论 2 343

推荐阅读更多精彩内容