# 跨多个通路的 DEGs 可视化

报错的原因是 scale_fill_manual() 提供的颜色向量 custom_colors 中的颜色数量不足以覆盖 geom_scatterpie 内使用的 cols 所对应的路径数量,导致了 “需要 11 个颜色,但只提供了 9 个” 的错误。

# 原因分析

  1. scale_fill_manual() 会同时影响所有使用 fill 映射的几何对象,包括:
    • geom_scatterpie (用于 pathways 和器官分布)
    • geom_label_repel (用于标签背景颜色)。
  2. 冲突
    • custom_colors 颜色向量只为 geom_scatterpie 的 pathways 提供了 9 种颜色。
    • 同时 geom_label_repel 使用 fill 映射来设置标签的背景色(红色和白色),这会造成颜色不足的错误。

# 解决方案

scale_fill_manual()geom_label_repel()fill 设置分开处理,确保路径( geom_scatterpie )和标签背景色互不干扰。

# 方法一:为 geom_scatterpie 使用 scale_fill_manual()

同时在 geom_label_repel() 中使用固定的 fill 值,不依赖 scale_fill_manual()

test <- g3 +
  ggforce::geom_mark_rect(aes(x = x, y = y, group = walktrap), color = "grey") +
  geom_scatterpie(aes(x = x, y = y, r = size + 0.1),
                  color = "transparent",
                  legend_name = "Pathway",
                  data = graphdata,
                  cols = pathways) +
  geom_scatterpie(aes(x = x, y = y, r = size),
                  color = "transparent",
                  data = graphdata, legend_name = "enrich",
                  cols = organ_columns) +
  scale_fill_manual(values = custom_colors, name = "Pathways") + # 仅控制 pathways 的填充颜色
  geom_node_point(shape = 19, size = 3, aes(filter = no_organ & type != "map")) +
  
  # 修复 geom_label_repel 的 fill,使其不受 scale_fill_manual 影响
  ggrepel::geom_label_repel(
    data = graphdata,
    aes(x = x, y = y, label = id),
    fill = ifelse(graphdata$is_top_node, "red", "white"), # 直接设置标签的背景颜色
    color = ifelse(graphdata$is_top_node, "white", "black"), # 文字颜色
    fontface = ifelse(graphdata$is_top_node, "bold", "plain"),
    size = 3,
    box.padding = 0.5,
    label.size = 0.5,
    segment.color = "grey50",
    segment.size = 0.5,
    max.overlaps = Inf,
    min.segment.length = 0
  ) +
  scale_colour_identity() +
  theme_void() + coord_fixed()

# 关键修正点

  1. geom_label_repel()
    • fill 参数:直接在 geom_label_repel 内部指定背景颜色,而不是通过 aes() 使用全局的 scale_fill_manual()
    • 这样标签背景色(红色和白色)不会受到 scale_fill_manual() 的影响。
  2. scale_fill_manual()
    • 仅用于 geom_scatterpie 控制饼图的填充颜色,不会干扰其他对象。