实现基于t-SNE坐标,然后用某item的值来体现在颜色上,同时显示基于item值过滤后的密度图
数据集如下:
现在用数据集的tSNE_1列作为点的x坐标,tSNE_2列作为点的y坐标,显示HALLMARK_SPERMATOGENESIS列每个点的分数
ggplot2简单定义一个点图叠加密度图的函数
Densityplt2 <- function(data,x,y,score,densitySelect){
samples = data; X=x ; Y=y ; DensitySelect = densitySelect
library(ggplot2)
jet.colors <- colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan", "#7FFF7F", "yellow", "#FF7F00", "red", "#7F0000")) #色盘
##核心绘图
max_expression=max(samples[,Score]) #点对应Score的最大值
min_expression=min(samples[,Score]) #点对应Score的最小值
arrondi <- function (x) ifelse(x>0, ifelse(x-trunc(x)>=0.5,trunc(x)+1,trunc(x)), ifelse(x-trunc(x)<=-0.5,trunc(x)-1,trunc(x)))
max_tsneX=arrondi(max(samples[,X]))+1 #设置X轴最大刻度
min_tsneX=arrondi(min(samples[,X]))-1 #设置X轴最小刻度
max_tsneY=arrondi(max(samples[,Y]))+1 #设置Y轴最大刻度
min_tsneY=arrondi(min(samples[,Y]))-1 #设置Y轴最小刻度
#############
p <- ggplot(samples, aes_string(x = X, y = Y)) +
#基于score绘制密度图
stat_density_2d(data=samples[samples[,Score]>DensitySelect,], aes(fill=..level..,alpha=..level..), geom='polygon', colour='darkgrey', n=50) +
#绘制点图
geom_jitter(aes(x = samples[,X], y = samples[,Y], color = samples[,Score]), size=1, alpha=0.7) +
###样式调整
labs(color = "Score") + # color legend
scale_colour_gradientn(colours = jet.colors(10), limits=c(min_expression, max_expression)) + #点对应的Value映射到颜色
xlab(X) +
ylab(Y) +
theme_bw() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + # remove grid
scale_alpha_continuous(range=c(0.1,0.5))+
scale_x_continuous(limits = c(min_tsneX, max_tsneX))+ #设置X轴刻度范围
scale_y_continuous(limits = c(min_tsneY, max_tsneY))+ #设置Y轴刻度范围
theme(
plot.title = element_text(size = 14),
axis.text.x = element_text(size = 14, color='black'),
axis.text.y = element_text(size = 14, color='black'),
strip.text.x = element_text(size = 14, color='black',angle=90),
strip.text.y = element_text(size = 14, color='black',angle=90),
axis.title.x = element_text(size = 14, color='black'),
axis.title.y = element_text(size = 14, angle=90))
return(p)
}
加载数据表(DataFrame):samples <- read.table("*.tsv",sep = '\t',header = T,row.names = 1)
然后调用函数Densityplt2(data = samples,score = "HALLMARK_SPERMATOGENESIS",x = "tSNE_1",y = "tSNE_2",densitySelect = 4)
选用数据表的“HALLMARK_SPERMATOGENESIS”列显示样本分数
方法引用自文献:
Pont, Frédéric et al. “Single-Cell Signature Explorer for comprehensive visualization of single cell signatures across scRNA-seq datasets.” Nucleic acids research vol. 47,21 (2019): e133. doi:10.1093/nar/gkz601