如何在ggplot2中设置两种不同字号的坐标轴标签
无需额外包实现双字号X轴标签
可以仅用ggplot2(及它依赖的grid包,属于tidyverse生态范畴)实现你要的效果,无需加载ggtext等额外包,以下是两种可行方案:
方案1:用annotation_custom添加独立文本元素
核心思路是隐藏默认轴标题,手动添加两个不同字号的文本元素,并调整绘图边距避免文本被截断:
library(tidyverse) library(grid) # ggplot2的依赖包,无需额外安装 mtcars |> ggplot(aes(x = wt, y = mpg)) + geom_point() + # 隐藏默认X轴标题 labs(x = "") + # 添加12pt的主标题文本 annotation_custom( grob = textGrob("Miles/(US) gallon", gp = gpar(fontsize = 12)), xmin = mean(mtcars$wt), xmax = mean(mtcars$wt), ymin = -2, ymax = -2 ) + # 添加8pt的补充说明文本 annotation_custom( grob = textGrob("[Min = 10.4, Max = 33.9]", gp = gpar(fontsize = 8)), xmin = mean(mtcars$wt), xmax = mean(mtcars$wt), ymin = -3.5, ymax = -3.5 ) + # 调整Y轴范围并关闭绘图裁剪,避免文本被截断 coord_cartesian(ylim = c(10, 35), clip = "off") + theme( # 调整底部边距,给自定义文本留出空间 plot.margin = margin(b = 25, unit = "pt") )
方案2:利用plotmath语法实现
ggplot2支持plotmath表达式,可以通过atop()将两行文本组合,并用textstyle()调整字号比例(8pt对应12pt的相对比例为0.67):
library(tidyverse) mtcars |> ggplot(aes(x = wt, y = mpg)) + geom_point() + labs( x = expression(atop("Miles/(US) gallon", textstyle("[Min = 10.4, Max = 33.9]", size = rel(0.67)))) ) + theme( axis.title.x = element_text(size = 12, parse = TRUE) )
内容的提问来源于stack exchange,提问作者captain
相关产品推荐
相关产品推荐

