没有数据,重现您的示例(您的休息等)有点困难。但是以下内容应该可以帮助您入门。
一个相当简单的解决方案是使用 ggplot2 的annotate()
函数将文本注释添加到垂直线之间的绘图面板中间。
# Load packages
library (ggplot2)
library(grid)
# Some data
df = data.frame(x = 1:10, y = 1:10)
# Base plot
p <- ggplot(df, aes(x,y)) + geom_point() +
scale_x_continuous(limits = c(0, 11), expand = c(0,0)) +
geom_vline(xintercept = 3) + geom_vline(xintercept = 7)
# Add the annotations
p + annotate("text", x = .5*(0+3), y = 11, label = "Part 1") +
annotate("text", x = .5*(3+7), y = 11, label = "Part 2") +
annotate("text", x = .5*(7+11), y = 11, label = "Part 3")
结果是:
或者就注释而言,接近您的示例图的解决方案。它用于annotation_custom()
绘制线条并将文本放置在绘图面板之外。即使注释是在绘图面板之外绘制的,注释的定位也是根据数据坐标进行的。基础图中的底部边距被加宽,以便为注释留出空间。该解决方案需要代码来覆盖 ggplot 将绘图元素剪辑到绘图面板。
不推荐使用更新 opts
;改为使用theme
。
# Base plot
p <- ggplot(df, aes(x,y)) + geom_point() +
scale_x_continuous(limits = c(0, 11), expand = c(0,0)) +
geom_vline(xintercept = 3) + geom_vline(xintercept = 7) +
theme(plot.margin = unit(c(1,1,4,1), "lines"))
# Create the text Grobs
Text1 = textGrob("Part 1")
Text2 = textGrob("Part 2")
Text3 = textGrob("Part 3")
# Add the annotations
# Segment 1
p1 = p +
annotation_custom(grob = linesGrob(), xmin = 0, xmax = 0, ymin = -1, ymax = -.75) +
annotation_custom(grob = linesGrob(), xmin = 0, xmax = 3, ymin = -1, ymax = -1) +
annotation_custom(grob = linesGrob(), xmin = 3, xmax = 3, ymin = -1, ymax = -.75) +
annotation_custom(grob = Text1, xmin = 0, xmax = 3, ymin = -1.25, ymax = -1.25)
# Segment 2
p1 = p1 +
annotation_custom(grob = linesGrob(), xmin = 3, xmax = 7, ymin = -1, ymax = -1) +
annotation_custom(grob = linesGrob(), xmin = 7, xmax = 7, ymin = -1, ymax = -.75) +
annotation_custom(grob = Text2, xmin = 3, xmax = 7, ymin = -1.25, ymax = -1.25)
# Segment 3
p1 = p1 +
annotation_custom(grob = linesGrob(), xmin = 7, xmax = 11, ymin = -1, ymax = -1) +
annotation_custom(grob = linesGrob(), xmin = 11, xmax = 11, ymin = -1, ymax = -.75) +
annotation_custom(grob = Text3, xmin = 7, xmax = 11, ymin = -1.25, ymax = -1.25)
# Code to override clipping
gt <- ggplot_gtable(ggplot_build(p1))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)
结果是: