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

如何为ggplot气泡图添加对应GO term的右侧次级Y轴?

在ggplot气泡图中添加匹配排序的次级Y轴(显示GO Term)

要实现左侧Y轴按neg.log10.P排序的Module与右侧对应GO Term的次级轴匹配,核心是让次级轴的标签位置和主Y轴的离散排序完全对应。由于ggplot的次级轴基于数值轴映射,我们可以将排序后的离散Module转换为数值位置,再通过sec_axis()关联对应的GO Term标签。

修改后的完整代码

# 生成模拟数据
df <- data.frame( 
  Module = c("black","blue","brown"), 
  P = c(1.068242e-12, 2.941035e-40, 6.975126e-12), 
  Bonferroni = c(3.915918e-07, 1.078113e-34, 2.556914e-06 ), 
  EnrichmentRatio = c(2.030865, 2.395059, 1.169325), 
  GO_term = c("GO term 1", "GO term 2", "GO term 3"), 
  "neg.log10.P" = c(11.97133, 39.53150, 11.15645) 
)

# 预先确定排序后的Module和对应GO_term顺序,让代码更清晰
ordered_modules <- reorder(df$Module, df$`neg.log10.P`)
ordered_go_terms <- df$GO_term[order(ordered_modules)]

# 生成带次级Y轴的气泡图
png("top10each_final_top.png", width= 8, height =  6, units = "in", res=300)
ggplot(df, aes(x=`neg.log10.P`, y=as.numeric(ordered_modules), size = EnrichmentRatio, fill = `neg.log10.P`)) +
  geom_point(shape = 21) + 
  scale_fill_viridis_c(option = "E", direction = -1) +
  # 配置主Y轴和次级Y轴
  scale_y_continuous(
    name = "Module",
    breaks = seq_along(ordered_modules),
    labels = ordered_modules,
    sec.axis = sec_axis(
      ~.,  # 次级轴与主轴使用完全相同的数值映射
      name = "GO Term",
      breaks = seq_along(ordered_go_terms),
      labels = ordered_go_terms
    )
  ) +
  labs(x = "-log10 P", title = "GO terms per module") +
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
    # 可选:调整次级轴标签颜色,区分主次轴
    axis.text.y.right = element_text(color = "gray50")
  )
dev.off()

关键逻辑说明

  1. 固定排序关系:通过reorder()得到按显著性排序后的Module顺序,再提取对应位置的GO_term,确保两者的排序完全匹配。
  2. 离散值转数值轴:将排序后的Module因子转换为数值(as.numeric(ordered_modules)),这样才能使用scale_y_continuous()创建次级轴。
  3. 次级轴映射:sec_axis(~.)表示次级轴与主轴共享同一数值刻度,通过breaks和labels将数值位置替换为对应的GO_term标签,保证位置完全对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 14:22:16