1) 使用 cowplot::draw_label()
解决方案
您也可以使用 cowplot
软件包中的注释函数 draw_label()
(在此讨论中提到)。我们可以多次调用 cowplot::draw_label()
以添加多行文本。当将 cowplot::draw_label()
与 cowplot::ggdraw()
合并使用时,它可以在画布/工作表上的任何位置进行注释,并且坐标范围从0到1(相对于整个画布)。
需要调整注释位置并为自定义轴标题留出足够的空间。
请注意,cowplot
软件包当前更改了默认ggplot主题,因此,如有必要,请在加载软件包后使用theme_set()
,如此处所述。
同时注意,函数cowplot::draw_label()
在底层使用了ggplot2::annotation_custom()
。下面的第二部分会详细介绍。
library(ggplot2)
library(cowplot)
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p <- p +
xlab("") +
theme(axis.title.x = element_text(size = 10,
margin = margin(t = 10, r = 0, b = 0, l = 0,
unit = "mm")))
line_1 <- "A long string of text for the purpose"
line_2 <- expression(paste("of illustrating my point" [reported]))
ggdraw(p) +
draw_label(line_1, x = 0.55, y = 0.075) +
draw_label(line_2, x = 0.55, y = 0.025)
请注意,可以将
cowplot::draw_label()
与关闭裁剪的
coord_cartesian(clip = "off")
结合使用,这样可以在画布的任何位置绘图。这次我们不再使用相对坐标,而是使用来自图形/数据的绝对坐标:
line_1b <- expression(bolditalic('First line'))
line_2b <- expression(integral(f(x)*dx, a, b))
p + coord_cartesian(clip = "off") +
draw_label(line_1b, x = 3.5, y = 8.2) +
draw_label(line_2b, x = 3.5, y = 6)
该示例是由reprex包(v0.2.1)于2019年1月14日创建的。
2) 使用ggplot2::annotation_custom()
解决方案
如前所述,cowplot::draw_label()
是ggplot2::annotation_custom()
的一个包装器。因此,我们可以直接使用ggplot2::annotation_custom()
,并结合设置裁剪关闭-coord_cartesian(clip = "off")
,这在合并该拉取请求后变得可用。
然而,这种方法更加冗长,需要更多的坐标参数,并且需要使用grid::textGrob()
。
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")
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包 (v0.2.1) 在2019-01-14创建的。
\n
。 - Gavin Simpson