今天绘制一下单细胞分析结果组织中细胞数量和细胞比例柱状图,代码如下:
- 安装需要的R包
install.packages(“Seurat”)
install.packages(“patchwork”)
install.packages(“reshape2”)
install.packages(“RcolorBrewer”)
install.packages(“scales”)
install.packages(“ggplot2”)
install.packages(“tidyverse”)
- 导入所需要的R包
library(Seurat)
library(patchwork)
library(reshape2)
library(RcolorBrewer)
library(ggplot2)
library(tidyverse)
library(scales)
- 代码展示
数据下载
wget https://cf.10xgenomics.com/samples/cell/pbmc3k/pbmc3k_filtered_gene_bc_matrices.tar.gz
tar -zxvf pbmc3k_filtered_gene_bc_matrices.tar.gz
#分析所需要的文件三个在filtered_gene_bc_matrices/hg19/
pbmc.data <- Read10X(data.dir = “filtered_gene_bc_matrices/hg19/”)
# Initialize the Seurat object with the raw (non-normalized data).
pbmc <- CreateSeuratObject(counts = pbmc.data, project = “pbmc3k”, min.cells = 3, min.features = 200)
# Normalizing the data
pbmc <- NormalizeData(pbmc, normalization.method = “LogNormalize”, scale.factor = 10000)
#Identification of highly variable features
pbmc <- FindVariableFeatures(pbmc, selection.method = “vst”, nfeatures = 2000)
all.genes <- rownames(pbmc)
pbmc <- ScaleData(pbmc, features = all.genes)
#Run non-linear dimensional reduction (UMAP/tSNE)
pbmc <- RunUMAP(pbmc, dims = 1:10)
#开始绘图
colourCount = length(unique(pbmc@meta.data$celltype))
getPalette = colorRampPalette(brewer.pal(9, “Set1”))
celltype_colors <- getPalette(colourCount)
#提取样本和细胞数据,并且进行长宽数据转换
plotC <- table(pbmc@meta.data$sample, pbmc@meta.data$celltype) %>% melt()
colnames(plotC) <- c(“Sample”, “CellType”,”Number”)
#绘制每个组织中细胞数目柱状图
pC1 <- ggplot(data = data_plotC, aes(x = Sample, y = Number, fill = CellType)) +
geom_bar(stat = “identity”, width=0.8,aes(group=CellType),position=”stack”)+
scale_fill_manual(values=celltype_colors) +
theme_bw()+
theme(panel.grid =element_blank()) +
labs(x=””,y=”Average number”)+
theme(axis.text = element_text(size=12, colour = “black”))+
theme(axis.title.y = element_text(size=12, colour = “black”))+
theme(panel.border = element_rect(size = 1, linetype = “solid”, colour = “black”))+
theme(axis.text.x = element_text(angle = 45,hjust = 0.8, vjust = 0.6))
#绘制每个组织中细胞比例柱状图
pC2 <- ggplot(data = plotC, aes(x = Sample, y = Number, fill = CellType)) +
geom_bar(stat = “identity”, width=0.8,aes(group=CellType),position=”fill”)+
scale_fill_manual(values=celltype_colors) +
theme_bw()+
theme(panel.grid =element_blank()) +
labs(x=””,y=”Cell proportion”)+
scale_y_continuous(labels = percent)+ ####用来将y轴移动位置
theme(axis.text = element_text(size=12, colour = “black”))+
theme(axis.title.y = element_text(size=12, colour = “black”))+
theme(panel.border = element_rect(size = 1, linetype = “solid”, colour = “black”))+
theme(axis.text.x = element_text(angle = 45,hjust = 0.8, vjust = 0.6))#让横轴上的标签倾斜45度
#两个图片进行拼图
pC <- pC1 + pC2 + plot_layout(ncol = 2, widths = c(1,1),guides = ‘collect’)
#保存图片
ggsave(pC,file=”plotC.pdf”,width = 7, height = 5)