这个问题混合了“如何在绘图区域之外进行注释”和“如何在 npc 坐标中进行注释”。因此,我提供了两种选择。
不幸的是,两者都需要一些试验和错误才能正确放置片段。对于选项 1,我们必须“猜测”的是 y 坐标,对于选项 2,它是 x!
为了让 y 的猜测工作稍微少一些,我尝试了一种相对于默认轴中断的位置方法。 using the fabulous information from this answer。这当然不是必须的,也可以简单地试错。
对于选项 2,我修改了一个函数 from user Allan Cameron's answer here。他提到了一种计算x和y的方法,我想可以使用标题,然后根据它放置注释。
library(ggplot2)
p <-
ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
ggtitle("lorem ipsum") +
theme(plot.margin = margin(t = 1.5, unit = "lines")) # this is always necessary
# OPTION 1
# semi-programmatic approach to figure out y coordinates
y_defaultticks <- with(mtcars, labeling::extended(range(wt)[1], range(wt)[2], m = 5))
y_default <- y_defaultticks[2] - y_defaultticks[1]
y_seg <- max(mtcars$wt) + 0.75 * y_default
p +
annotate(geom = "segment", x = - Inf, xend = 12, y = y_seg, yend = y_seg,
color = "red", size = 5) +
coord_cartesian(clip = "off", ylim = c(NA, max(mtcars$wt)),
xlim = c(min(mtcars$mpg), NA))
# OPTION 2
annotate_npc <- function(x, y, height, width, ...) {
grid::grid.draw(grid::rectGrob(
x = unit(x, "npc"), y = unit(y, "npc"), height = unit(height, "npc"), width = unit(width, "npc"),
gp = grid::gpar(...)
))
}
p
annotate_npc(x = 0.07, y = 1, height = 0.05, width = 0.05, fill = "red", col = NA)
由reprex package (v0.3.0) 于 2021-01-02 创建