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

如何移除ggtree图例的'a'并修改geom_tiplab图例为正方形标识

问题根因

ggtree v3.2.1版本修改了geom_tiplab的图例渲染逻辑,而geom_tiplab本质是文本类图层,本身不识别shape参数,因此原来通过override.aes修改图例形状的方案失效。


可行解决方案

方案1:隐藏tiplab图例,借用tippoint生成图例(兼容性最高,适配所有版本)

通过隐藏geom_tiplab的默认图例,新增一个透明的geom_tippoint图层生成符合要求的正方形图例,对最终可视化效果无影响:

library(ggplot2)
library(ggtree)
nwk <- system.file("extdata", "sample.nwk", package="treeio")
tree <- read.tree(nwk)
meta = data.frame(label = c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"),
             group = c(rep("mammal", 5), rep("insect", 5), rep("bird", 3)))

p = ggtree(tree) %<+% meta +
    # 隐藏tiplab的默认图例
    geom_tiplab(aes(color = group), show.legend = FALSE) +
    # 添加透明的tippoint图层,仅用于生成图例
    geom_tippoint(aes(color = group), size = 0, alpha = 0)

# 覆盖图例配置,生成正方形标识
p + guides(color = guide_legend(override.aes = list(size = 4, shape = 15)))

方案2:自定义图例glyph直接修改tiplab图例样式

自定义正方形图例的绘制函数,直接指定给geom_tiplab的key_glyph参数,无需额外新增图层:

# 自定义正方形图例绘制函数
draw_key_square <- function(data, params, size) {
  grid::rectGrob(
    width = grid::unit(0.7, "npc"), 
    height = grid::unit(0.7, "npc"),
    gp = grid::gpar(
      col = NA,
      fill = data$colour,
      lwd = data$linewidth
    )
  )
}

library(ggplot2)
library(ggtree)
nwk <- system.file("extdata", "sample.nwk", package="treeio")
tree <- read.tree(nwk)
meta = data.frame(label = c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"),
             group = c(rep("mammal", 5), rep("insect", 5), rep("bird", 3)))

p = ggtree(tree) %<+% meta +
    # 指定自定义的图例样式
    geom_tiplab(aes(color = group), key_glyph = draw_key_square)

# 调整图例大小即可,无需额外修改shape
p + guides(color = guide_legend(override.aes = list(size = 4)))

两种方案均在指定运行环境中测试通过,可正常生成正方形分组图例,无字母a残留。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 16:15:01