如何调整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=10)
p <- p + stat_cor(aes(label = ..rr.label..), color = "red", geom = "label", digits = 2, 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
相关产品推荐
相关产品推荐

