[关闭]
@agpwhy 2022-12-10T04:33:26.000000Z 字数 1995 阅读 189

王胖的生信笔记第五十一期:改造R的函数

​ 做单细胞测序数据分析不知道Seurat就好像五官科学生不知道耳朵在哪里,这是几乎不可能发生的事情。Seurat是法国一个画家,有很独特的作画风格。搜一下他的画你就明白为啥Satija团队做的这个包取了这个名字了。

​ 其实好好看Seurat的说明书(Satija的官方网站),许多常用的改动和可视化需要调整的都已经开放了。但确实还是又时候无法准确实现自己的需求。比如前段时间有老师让我看看《Allergic inflammatory memory in human respiratory epithelial progenitor cells》文章里这个咋做:

1

​ 实际上我一开始的思路是用split.by这个参数去调整。但是当你实际操作时候会发现并不是这个文章里的感觉。文章里时每一个对应的feature gene在对应的细胞类型中并列展示两组的数据。乍看上去有点难度,但实际上还是可以利用Seurat作图完的数据,进行下一步操作。试看此例。

首先准备环境+提取信息

  1. library(Seurat)
  2. library(stringr)
  3. library(ggplot2)
  4. p <- DotPlot(scRNAsub,features=c("CD8A","CD3E","NKG7"),
  5. group.by="RNA_snn_res.0.2",split.by = "orig.ident",cols = my36colors)+ coord_flip()
  6. exp <- p$data

需要注意的是,seurat格式的文件需要有样本分组信息(这里是“orig.ident”)和细胞类型信息(这里是“RNA_snn_res.0.2”)。这样提取的就是对应所需的所有数据了。

进一步处理

  1. library(forcats)
  2. exp$features.plot <- as.factor(exp$features.plot)
  3. exp$features.plot <- fct_inorder(exp$features.plot)
  4. split_b<-str_split(exp$id,"_")
  5. b<-sapply(split_b,"[",1)
  6. c<-sapply(split_b,"[",2)
  7. exp$id <- b
  8. exp$new <- c
  9. exp$features.plot <- paste0(exp$features.plot,"_",exp$new)

需要注意的是,这里提取结束出现的就是每个基因对应的两组数据了

作图调整

这个需要大家再回去看下ggplot2的相关说明。当然最后的展示成果和文章还是稍有区别,这个可以在ppt或者ai里面再细调了。

  1. p <- ggplot(exp,aes(x=id,y=features.plot))+geom_point(aes(size=`pct.exp`,
  2. color=`new`))+theme_bw()+
  3. theme(panel.grid = element_blank(),
  4. axis.text.x=element_text(angle=90,hjust=1,vjust = 0.5))+ coord_flip()

2

我枕边分组比较多,所以用的颜色相对较多。也可以只有两种颜色的。

3

拓展

其实很多时候可以通过trace()函数来调取函数源代码,然后做一些琢磨。比如cellchat做出来的很多图你可能也不知道是咋算出来的。就像官方教程里这张图右侧的barchat到底具体数值是多少?当你想去探究的时候怎么办呢?

4

使用trace(CellChat::netAnalysis_signalingRole_heatmap,edit=T)研究后发现,可以这样提取出需要的数据。

  1. library(CellChat)
  2. object <- X2Cellchat
  3. slot.name = "netP"
  4. centr <- slot(object, slot.name)$centr
  5. outgoing <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))
  6. incoming <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))
  7. dimnames(outgoing) <- list(levels(object@idents), names(centr))
  8. dimnames(incoming) <- dimnames(outgoing)
  9. for (i in 1:length(centr)) {
  10. outgoing[, i] <- centr[[i]]$outdeg
  11. incoming[, i] <- centr[[i]]$indeg
  12. }
  13. # outgoing的数据
  14. mat <- t(outgoing)
  15. # incoming的数据
  16. mat <- t(incoming)
  17. # all的数据
  18. mat <- t(outgoing + incoming)
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注