title: ‘单细胞数据如何绘制stacked violin?’date: 2021-01-21 17:05:37
tags: [R,|,SingleCell,|,Seurat,|,violin]
published: false
hideInList: false
feature:
isTop: false

Python的Scanpy包和Seurat包一样,是单细胞数据处理的利器,其中,Scanpy中有一种堆积的小提琴图,可以很好的展示marker的表达情况,但是在Seurat中并没有内置命令。因此,我自己尝试提取数据并用ggplot2包来画该图。

首先来展示以下画图的成果,如图

那么直接上命令吧!

  1. ###载入需要的R包
  2. library(Seurat)
  3. library(dplyr)
  4. library(tidyr)
  5. library(ggplot2)
  6. ##load测试数据
  7. data<-readRDS("cluster_1.afterclu.rds")
  1. ##第一个函数从Seurat对象中获取表达值并转化为需要的格式tidy
  2. gotData<-function(seurat.obj,features,groups){
  3. mat<-GetAssayData(data,assay = "RNA",slot = "data")[features,]
  4. plotData<-mat%>%
  5. as.data.frame()%>%
  6. tibble::rownames_to_column(var="gene")%>%
  7. as_tibble()%>%
  8. tidyr::pivot_longer(names_to = "cell",values_to="exp",cols=2:(ncol(mat)+1))
  9. cellmeta<-data@meta.data%>%
  10. tibble::rownames_to_column(var="cell")%>%
  11. as_tibble()%>%
  12. select(cell,sym(groups))
  13. plotData<-plotData%>%
  14. left_join(cellmeta,by="cell")%>%
  15. setNames(c("gene","cell","value","cellID"))
  16. plotData
  17. }
  18. ##第二个函数画图
  19. plot_stacked_violin<-function(plotData,xlab,ylab,cols){
  20. ggplot(plotData,aes(y=cellID,x=value,fill=cellID))+
  21. geom_violin()+
  22. facet_wrap(.~gene)+
  23. theme_test()+
  24. xlab(xlab)+
  25. ylab(ylab)+
  26. scale_fill_manual(values = cols)+
  27. theme(panel.spacing=unit(0,"cm"),
  28. strip.background = element_rect(fill="transparent",color = "white"),
  29. axis.text.x = element_blank(),
  30. axis.ticks.x = element_blank(),
  31. panel.border = element_rect(size=0.7,colour = "black"),
  32. strip.text = element_text(size=10,face = "italic"),
  33. axis.text.y = element_text(size = 11.5,face="bold"),
  34. axis.title.y = element_text(size = 13))+
  35. NoLegend()
  36. }

下面是使用方法

  1. plot_stacked_violin(gotData(data,c("CD7","KLRB1","NKG7"),"integrated_snn_res.0.1"),"","Cell cluster",c("#8dd3c7","#ffffb3","#bebada","#fb8072"))

禁止转载!