如何在ggdist::stat_spike的竖线顶部添加文本标签?
给stat_spike竖线加基因名标签的两种实现方法
问题说明
我用X轴为连续基因表达数据(log2TPM)、Y轴为分类分组的数据集,写了下面的ggplot代码画半眼图+箱线图+竖线:
ggplot(merged_data, aes(x = log2TPM, y=categ)) + ggdist::stat_slab(justification = -.2, width = .6) + geom_boxplot(outlier.color = NA, width = .15) + ggdist::stat_spike(at=gene_data$log2TPM, justification = -.2)
现在要给stat_spike生成的每条竖线顶部加gene_data$gene_name的文本标签,有两种需求:
- 把标签固定在绘图区的上边缘
- 让标签跟半眼图(stat_slab)的位置对齐
数据集样例:
> merged_data %>% select(log2TPM,gene_name,categ) %>% head() log2TPM gene_name categ 1 3.357552 TSPAN6 All_13421 2 4.508429 DPM1 All_13421 3 1.650765 SCYL3 All_13421 4 0.926000 C1orf112 All_13421 5 4.563768 CFH All_13421 6 4.861955 FUCA2 All_13421
方案1:标签固定在绘图区上边缘
直接把标签定位到绘图区顶部,配合参数调整位置避免被裁剪:
# 先画出基础图 p <- ggplot(merged_data, aes(x = log2TPM, y=categ)) + ggdist::stat_slab(justification = -.2, width = .6) + geom_boxplot(outlier.color = NA, width = .15) + ggdist::stat_spike(at=gene_data$log2TPM, justification = -.2) # 添加顶部固定标签 p + geom_text( data = gene_data, aes(x = log2TPM, y = Inf, label = gene_name), vjust = 1.2, # 控制标签在竖线顶部的垂直距离 size = 3, hjust = 0.5 ) + coord_cartesian(clip = "off") # 防止标签超出绘图区被切掉
要点:
y = Inf直接把标签钉在绘图区最上方coord_cartesian(clip = "off")必须加,不然标签会被绘图区边界裁掉- 用
vjust微调标签和竖线顶部的间距
方案2:标签跟随半眼图位置
把标签放在半眼图的外侧,和半眼图对齐,需要把分类变量转成数值后加偏移量:
ggplot(merged_data, aes(x = log2TPM, y=categ)) + ggdist::stat_slab(justification = -.2, width = .6) + geom_boxplot(outlier.color = NA, width = .15) + ggdist::stat_spike(at=gene_data$log2TPM, justification = -.2) + geom_text( data = gene_data, aes(x = log2TPM, y = as.numeric(factor(categ)) - 0.3, label = gene_name), hjust = 0.5, size = 3 )
要点:
as.numeric(factor(categ))把分类组转成对应的数值位置- 减去的
0.3是偏移量,可根据半眼图的width参数调整,确保标签对齐半眼图外侧 - 每个组的标签会自动匹配对应的半眼图位置
内容的提问来源于stack exchange,提问作者ricardo3889
相关产品推荐
相关产品推荐

