首页 > 解决方案 > 使用不同数据集时文本相对于绘图区域的一致定位

问题描述

我生成了几个图,其中数据可能具有不同xy范围。我希望在所有绘图中放置一个文本注释,相对于绘图区域的位置完全相同。

第一个图的示例,我在其中添加文本并以数据为单位annotate定位它:xy

library(tidyverse)
ggplot(mpg) + 
  geom_point(aes(displ, hwy)) +
  annotate("text", x = 6, y = 20, label = "example watermark", size = 8) +
  ggsave(filename = "mpg.jpg", width = 10, height = 9, dpi = 60)

在此处输入图像描述

x然后根据与第一个图不同且y范围不同的另一个数据集创建第二个图。

无需反复试验,将文本放置在相对于绘图区域完全相同的位置的最佳方法是什么?

ggplot(iris) + 
  geom_point(aes(Petal.Width, Petal.Length)) +
  # I don't want to hardcode x and y in annotate
  # annotate("text", x = 6, y = 20, label = "example watermark", size = 8) +
ggsave(filename = "iris.jpg", width = 10, height = 9, dpi = 60)

在此处输入图像描述

标签: rggplot2textgeom-text

解决方案


您可以使用annotation_custom. 这允许您grob在绘图窗口的指定坐标处绘制图形对象 ( )。只需以“npc”为单位指定位置,从左下角的 (0, 0) 缩放到窗口右上角的 (1, 1):

library(ggplot2)

mpg_plot   <- ggplot(mpg) + geom_point(aes(displ, hwy))
iris_plot  <- ggplot(iris) + geom_point(aes(Petal.Width, Petal.Length))
annotation <- annotation_custom(grid::textGrob(label = "example watermark",
                                               x = unit(0.75, "npc"), y = unit(0.25, "npc"),
                                               gp = grid::gpar(cex = 2)))
mpg_plot  + annotation

iris_plot + annotation

reprex 包于 2020-07-10 创建(v0.3.0)


推荐阅读