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

如何用R的gggenes包绘制无重叠、按起始位排列的同线性基因图

解决gggenes绘图基因重叠及需求适配方案

核心问题解决:生成无重叠的连续基因位置

原始数据的START_POSITION和END_POSITION存在重叠,导致基因箭头挤在一起。我们需要对每个物种的基因按起始位置排序后,重新计算一组连续坐标,让基因紧密相邻且无重叠。用dplyr做分组处理:

library(dplyr)
library(gggenes)
library(ggplot2)

# 预处理数据:为每个物种生成无重叠的连续基因位置
cnr1_processed <- cnr1_synteny_representative %>%
  group_by(SPECIES) %>%
  # 按原始起始位置排序
  arrange(START_POSITION) %>%
  # 计算新的连续位置:保留基因原长度,依次排列
  mutate(
    gene_length = END_POSITION - START_POSITION,
    new_xmin = cumsum(ifelse(row_number() == 1, 0, lag(gene_length))),
    new_xmax = new_xmin + gene_length,
    # 映射orientation到gggenes要求的方向(1为右,-1为左)
    direction = ifelse(orientation == "+", 1, -1)
  ) %>%
  ungroup()

适配所有需求的绘图代码

调整ggplot代码,满足所有指定需求:

ggplot(cnr1_processed, 
       aes(xmin = new_xmin, xmax = new_xmax, 
           y = SPECIES, fill = SYMBOL, direction = direction)) +
  # 绘制带方向的基因箭头
  geom_gene_arrow() +
  # 在箭头上添加基因名称标签,调整对齐方式避免遮挡
  geom_gene_label(aes(label = SYMBOL), size = 3, align = "left") +
  # 每个物种单独占一行,x轴自由缩放,标签放在左侧
  facet_wrap(~ SPECIES, scales = "free_x", ncol = 1, strip.position = "left") +
  # 按Symbol字段自定义着色
  scale_fill_manual(values = mycolors) +
  # 使用gggenes主题,优化细节
  theme_genes() +
  theme(
    legend.position = "none",
    # 调整左侧物种标签的显示样式
    strip.text.y.left = element_text(angle = 0, hjust = 1),
    strip.background = element_blank()
  ) +
  # 隐藏无意义的x轴刻度(新坐标为连续排列,原始坐标参考价值低)
  scale_x_continuous(breaks = NULL, labels = NULL) +
  labs(x = NULL, y = NULL)

关键细节说明

  • 无重叠排列:通过new_xmin和new_xmax的计算,保证每个物种内的基因按原始顺序紧密排列,彻底消除重叠。
  • 基因方向控制:通过direction字段映射到geom_gene_arrow的参数,精准实现+向右、-向左的箭头方向。
  • 物种标签布局:strip.position = "left"将物种标签移至左侧,配合文字方向调整,让标签更易读。
  • 基因标签优化:geom_gene_label自动将标签嵌入箭头内部,align = "left"保证标签对齐箭头起始端,避免互相遮挡。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:55:18