You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot2绘图区特定坐标处添加对应DNA区域的氨基酸序列色块?

在ggplot2折线图中添加氨基酸序列对应色块标注

问题背景

已通过ggplot2生成x轴展示DNA序列的折线图,现有长度为4的氨基酸序列aaseq <- "WXYZ",对应DNA序列的起始位置为5、结束位置为17(每个氨基酸对应3个DNA碱基),需在图中对应位置添加色块标注。

实现方法

可以通过geom_rect()快速添加色块,核心是先计算每个氨基酸对应的DNA碱基在x轴(time)上的坐标区间,再生成色块数据集并添加到图中,步骤如下:

修改后的完整代码

library(ggplot2)
library(dplyr)
library(ggtext)

# 原始数据与绘图基础设置
myseq <- "AGAATATTATACATTCATCT"
set.seed(123)
mydata <- data.frame(time=1:100, value=rnorm(100, mean=10, sd=2))
indices <- seq(5, 100, length.out=20)
seqsplit <- unlist(strsplit(myseq, ""))
ind_df <- data.frame(call=seqsplit, time=indices)
final_df <- dplyr::left_join(mydata, ind_df, by="time")
xcolors <- ifelse(seqsplit=="A", "green", ifelse(seqsplit=="C", "blue", ifelse(seqsplit=="G", "black", "red")))

# 处理氨基酸序列与对应色块位置
aaseq <- "WXYZ"
# 拆分每个氨基酸对应的DNA碱基区间,映射到x轴time坐标
aa_positions <- data.frame(
  aa = strsplit(aaseq, "")[[1]],
  dna_start = seq(5, 17-2, by=3),
  dna_end = seq(5+2, 17, by=3)
) %>%
  mutate(
    x_start = indices[dna_start],
    x_end = indices[dna_end],
    # 定义色块在y轴的位置(可根据需求调整高度和上下位置)
    y_start = 5,
    y_end = 6
  )

# 绘制图形
P <- ggplot(final_df, aes(x=time, y=value)) +
  geom_line(linewidth=0.5) +
  # 添加氨基酸对应色块
  geom_rect(data=aa_positions, aes(xmin=x_start, xmax=x_end, ymin=y_start, ymax=y_end),
            fill="orange", alpha=0.5, inherit.aes=FALSE) +
  # 可选:添加氨基酸标签
  geom_text(data=aa_positions, aes(x=(x_start+x_end)/2, y=y_end+0.3, label=aa),
            fontface="bold", inherit.aes=FALSE) +
  scale_x_continuous(breaks=indices, labels=seqsplit) +
  scale_y_continuous(limits=c(5,17)) +
  theme_light() +
  theme(axis.title.x=element_blank(),
        axis.text.x=element_markdown(face="bold", color=xcolors))

# 输出PDF
grDevices::pdf(file="test_with_aa.pdf", height=3, width=10)
print(P)
grDevices::dev.off()

关键说明

  • aa_positions数据集:通过DNA碱基的起始/结束索引,映射到x轴的time坐标,同时定义色块的y轴范围,可根据需求调整高度和位置
  • geom_rect()的inherit.aes=FALSE:避免继承主图的x/y映射,使用自身数据集的坐标
  • 调整fill和alpha参数可以改变色块的颜色和透明度,避免遮挡折线
  • 可选的geom_text()用于添加氨基酸标签,位置可通过y参数调整

内容的提问来源于stack exchange,提问作者DaniCee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 17:55:20