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

如何调整stat_cor标签边距?解决文本放大后R²溢出问题

解决ggpubr stat_cor标签文本溢出问题

我在使用ggplot2结合ggpubr包绘制iris数据集散点图时,遇到了stat_cor标签显示异常的问题:通过stat_cor添加R²标签(调用..rr.label..),当标签文本size设为3时显示正常,但调整为10后,R²文本直接溢出白色标签框,且无法居中。尝试调整label.size参数只能放大标签边框,完全解决不了内边距适配的问题,需要调整标签内边距让文本适配标签框。

正常显示的代码(size=3)

library(ggplot2)
library(ggpubr)

# 绘制散点图
p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point() 

# 添加R²标签
p <- p + stat_cor(aes(label = ..rr.label..), 
                  color = "red", geom = "label", digits = 2, size = 3)

size=3时标签显示正常

出现问题的代码(size=10)

p <- p + stat_cor(aes(label = ..rr.label..), 
                  color = "red", geom = "label", digits = 2, size = 10)

size=10时文本溢出标签框

解决方案

因为stat_cor使用geom="label"时,底层调用的是ggplot2的geom_label,所以可以直接传递label.padding参数来调整标签内边距。这个参数需要用unit()函数指定长度单位,比如设置为unit(1, "lines")就能给大尺寸文本留出足够的内边距:

library(ggplot2)
library(ggpubr)

p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point() +
  stat_cor(aes(label = ..rr.label..), 
           color = "red", geom = "label", digits = 2, size = 10,
           label.padding = unit(1, "lines")) # 调整标签内边距

设置后,大尺寸的R²文本就能完全适配白色标签框,且居中显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:57:33