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

ggplot2移除图例时annotate注解被同步删除的解决方法咨询

问题原因

你观察到的「注解被删除」是视觉误解:注解并没有被移除,只是关闭图例后,ggplot默认收回了原本留给图例的右侧空白边距,你设置在x=7位置的文本注解落到了画布可视区域之外,因此无法显示。

解决方法

在原有代码基础上,手动添加theme配置固定右侧绘图边距即可,同时还可以将重复的分割线、注解逻辑合并为向量传值,简化代码:

library(ggplot2)
library(grid) # 用到unit函数需要加载该包

fmsft <- ggplot(Fboxm, aes(test, count))

fmsft + geom_boxplot(aes(fill = test), show.legend = FALSE) + 
  labs(x="Test", y=expression("Estimated VO"["2Max"])) + 
  # 批量生成分割线
  geom_hline(yintercept = c(23.9, 28.6, 34.6, 40.6, 46.5, 56), size = 1.3) + 
  # 批量生成注解
  annotate("text", 
           label = c("Very Poor", "Poor", "Fair", "Good", "Excellent", "Superior"),
           x = 7, 
           y = c(23.9, 28.6, 34.6, 40.6, 46.5, 56)) +
  coord_cartesian(xlim = c(0,6), clip = "off") +
  # 核心配置:调整边距,四个参数对应上、右、下、左的边距,可按需调整右侧数值
  theme(plot.margin = unit(c(0.5, 2, 0.5, 0.5), "cm"),
        legend.position = "none")

效果说明

调整边距后,右侧会预留足够空间显示x=7位置的注解,同时不会显示图例,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:06:03