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

如何在ggplot绘图中固定textbox文本框在窗口左下角并解决报错

问题修复方案

你遇到的报错是geom_textbox()未指定对齐参数、或ggtext包版本过低导致的视口调用异常,按以下方式修改代码即可实现文本框固定在绘图区左下角、不受窗口尺寸影响的效果:

library(dplyr)
library(ggplot2)
library(ggtext)
library(ggdist)
set.seed(1)

DF = rbind(data.frame('Label' = 'A', val = rnorm(200, 5)), data.frame('Label' = 'B', val = rnorm(500, 10)))

DF %>%
ggplot(aes(x=Label, y=val, fill=Label, alpha = 1)) +
stat_dots() +
geom_textbox(
  x = -Inf, 
  y = -Inf, 
  label = 'My text', 
  hjust = 0, 
  vjust = 0, 
  width = unit(0.4, "npc"), 
  height = unit(0.04, "npc"), 
  box.margin = unit(c(5, 5, 5, 5), "pt")
) 

参数说明

  • hjust = 0、vjust = 0是核心修改,将文本框的左下角设置为对齐锚点,和你指定的x=-Inf、y=-Inf(绘图区域左下角坐标)完全对齐,画布缩放时位置不会偏移。
  • 若修改后仍有报错,先执行install.packages("ggtext")升级到最新版ggtext包,重启R会话后再运行即可。

可选:固定在整张画布左下角

如果你需要文本框固定在整张画布(包含坐标轴外的边距区域)的左下角,可使用annotation_custom()结合textbox_grob实现:

library(grid)
# 先创建文本框grob
text_box <- textbox_grob(
  label = "My text",
  x = 0.01, 
  y = 0.01,
  hjust = 0,
  vjust = 0,
  width = unit(0.4, "npc"),
  height = unit(0.04, "npc")
)

# 绘图时调用
DF %>%
ggplot(aes(x=Label, y=val, fill=Label, alpha = 1)) +
stat_dots() +
annotation_custom(text_box)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:15:03