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

ggplot2绘图:图例下方添加格式化文本框及保存带注释的图

ggplot2 绘图外部文本编辑解决方案

1. 在图例下方添加可控制换行的左对齐多行文本框

无需手动调整注释,可通过grid包的textGrob结合annotation_custom实现,支持手动/自动换行与左对齐:

  • 手动换行:在文本中插入\n分隔行
  • 自动换行:用stringr::str_wrap按指定宽度拆分文本
  • 设置hjust=0实现左对齐,通过x/y参数定位到图例下方,同时调整plot.margin给注释留出空间

示例代码:

library(ggplot2)
library(grid)
library(stringr)

# 示例数据
df <- data.frame(
  x = rnorm(50),
  y = rnorm(50),
  group = rep(c("A", "B"), 25)
)

# 基础绘图(图例置底)
p <- ggplot(df, aes(x, y, color = group)) +
  geom_point() +
  theme(
    legend.position = "bottom",
    plot.margin = margin(10, 10, 50, 10) # 底部预留注释空间
  )

# 手动换行文本
txt <- "第一行注释内容\n第二行左对齐文本\n第三行补充说明"
# 或自动换行:txt <- str_wrap("这是一段较长的注释文本,需要按指定宽度自动换行并左对齐显示在图例下方。", width=25)

# 创建左对齐文本grob
text_grob <- textGrob(
  label = txt,
  x = unit(0.02, "npc"),
  y = unit(0.03, "npc"),
  hjust = 0,
  gp = gpar(fontsize = 10)
)

# 添加到绘图
p <- p + annotation_custom(text_grob)

2. 对annotation_custom添加的文本实现部分内容加粗

普通textGrob不支持markdown格式,改用gridtext包的richtext_grob,直接用**包裹需要加粗的内容即可:

示例代码:

library(gridtext)

# 带加粗格式的文本
bold_txt <- "样本规则说明:A1-**CV**.CV 为交叉验证组,B1-**Train**.Train 为训练组"

# 创建富文本grob(去掉边框)
richtext_grob <- richtext_grob(
  text = bold_txt,
  x = unit(0.02, "npc"),
  y = unit(0.03, "npc"),
  hjust = 0,
  gp = gpar(fontsize = 10),
  box_gp = gpar(col = NA)
)

# 替换原有文本注释
p <- p + annotation_custom(richtext_grob)

3. 用ggsave保存包含自定义注释的完整绘图

由于自定义注释可能位于默认绘图区域外,直接保存ggplot对象会被裁剪,有两种解决方法:

方法一:转换为grob对象后保存

# 将绘图转换为grob对象
g <- ggplotGrob(p)

# 保存完整绘图
ggsave("full_plot.png", g, width = 8, height = 6, dpi = 300)

方法二:调整绘图边距后直接保存

只要提前通过plot.margin给注释留出足够空间,直接保存ggplot对象即可包含全部内容:

ggsave("full_plot.png", p, width = 8, height = 6, dpi = 300)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:12:50