1) 使用cowplot::draw_label() 的解决方案
也可以使用cowplot 包中的注释函数draw_label()(在this 讨论中建议)。我们可以调用cowplot::draw_label() 尽可能多的文本行。当cowplot::draw_label()与cowplot::ggdraw()结合使用时,它可以在canvas/sheet上的任意位置进行注释,坐标范围为0到1(相对于整个canvas)。
需要调整注释位置并为自定义轴标题留出足够的空间。
请注意,cowplot 包当前更改了默认的 ggplot 主题,因此,如果需要,请在加载包后使用 theme_set(),如 here 所述。
还要注意,函数 cowplot::draw_label() 在底层使用 ggplot2::annotation_custom()。我将在下面的第二部分中详细介绍这一点。
library(ggplot2)
library(cowplot)
#>
#> Attaching package: 'cowplot'
#> The following object is masked from 'package:ggplot2':
#>
#> ggsave
# If needed, revert to default theme (cowplot modifies the theme);
# theme_set(theme_grey())
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
# Make enough space for the custom two lines axis title
p <- p +
xlab("") + # empty label
# Tweak the margins (push the label down by forcing a wider top margin)
theme(axis.title.x = element_text(size = 10, # also adjust text size if needed
margin = margin(t = 10, r = 0, b = 0, l = 0,
unit = "mm")))
# The two lines we wish on the plot
line_1 <- "A long string of text for the purpose"
line_2 <- expression(paste("of illustrating my point" [reported]))
# Or avoid paste() (is not actually needed)
# line_2 <- expression("of illustrating my point" [reported])
# Call cowplot::draw_label two times to plot two lines of text
ggdraw(p) +
draw_label(line_1, x = 0.55, y = 0.075) + # use relative coordinates for positioning
draw_label(line_2, x = 0.55, y = 0.025)
请注意,cowplot::draw_label() 也可以与设置裁剪关闭结合使用,coord_cartesian(clip = "off"),它允许在画布上的任何位置进行绘图。这次我们不再使用相对坐标,而是使用绘图/数据中的坐标(绝对坐标):
# Other two expressions
line_1b <- expression(bolditalic('First line'))
line_2b <- expression(integral(f(x)*dx, a, b))
p + coord_cartesian(clip = "off") + # allows plotting anywhere on the canvas
draw_label(line_1b, x = 3.5, y = 8.2) + # use absolute coordinates for positioning
draw_label(line_2b, x = 3.5, y = 6)
由reprex package (v0.2.1) 于 2019 年 1 月 14 日创建
2) 使用ggplot2::annotation_custom() 的解决方案
如前所述,cowplot::draw_label() 是ggplot2::annotation_custom() 的包装器。因此,我们可以直接使用ggplot2::annotation_custom() 来代替cowplot::draw_label(),并结合设置剪裁-coord_cartesian(clip = "off"),这可以通过合并this pull request 来实现。
但是,这种方法更冗长,有更多的坐标参数,我们需要使用grid::textGrob()。
# Some other two lines we wish on the plot as OX axis title
line_1c <- expression("Various fonts:" ~ bolditalic("bolditalic") ~ bold("bold") ~ italic("italic"))
line_2c <- expression("this" ~~ sqrt(x, y) ~~ "or this" ~~ sum(x[i], i==1, n) ~~ "math expression")
# the ~~ ads a bit more space than ~ between the expression's components
p + coord_cartesian(clip = "off") +
annotation_custom(grid::textGrob(line_1c), xmin = 3.5, xmax = 3.5, ymin = 7.3, ymax = 7.3) +
annotation_custom(grid::textGrob(line_2c), xmin = 3.5, xmax = 3.5, ymin = 5.5, ymax = 5.5)
由reprex package (v0.2.1) 于 2019 年 1 月 14 日创建