ggplot2 添加注释

主要介绍ggplot2添加图注释

使用annotate()

ggplot2 中提供各种灵活的方式添加注释,比如使用geom_text, geom_rect, geom_line等,但我更推荐使用annotate()进行标注。

annotate()使用vectors中的值进行几何对象数据映射,相比geom_类从data frame映射数据更加轻便[1]

标注类型

annotate()通过第一个参数指定标注类型:

"text","rect","segment","pointrange","curve"

实现方式

  • 以坐标形式指定标注放置位置

    p + annotate(
        geom = "curve", x = 4, y = 35, xend = 2.65, yend = 27, 
        curvature = .3, arrow = arrow(length = unit(2, "mm"))
      ) +
      annotate(geom = "text", x = 4.1, y = 35, label = "subaru")

  • 对于"rect"型标注,通过设置 ymin/ymax+/-Inf,绘制背景分区样式[2]

    p + geom_rect(
        aes(xmin = start, xmax = end, fill = party), 
        ymin = -Inf, ymax = Inf, alpha = 0.2, 
        data = presidential
      ) + 
      scale_fill_manual(values = c("blue", "red"))

  • 在Facet增加标注参考此文。

Reference