Vic*_*ica 10 text r ggplot2 geom-text
我生成的几个地块,其中数据可能有不同x和y范围。我希望在所有图中放置一个文本注释,相对于 plot area完全相同的位置。
第一标绘,其中I添加具有文本的实施例annotate和位置将其与x和y在所述数据单元:
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)
Run Code Online (Sandbox Code Playgroud)
然后根据另一个数据集创建第二个图,其中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)
Run Code Online (Sandbox Code Playgroud)
您可以使用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
Run Code Online (Sandbox Code Playgroud)

iris_plot + annotation
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020 年 7 月 10 日创建
该ggpmisc包有一些方便的功能,其中坐标以“npc”图形单位给出。
您可以尝试geom_text_npc(或其兄弟geom_label_npc),“旨在用于相对于绘图的物理尺寸定位文本”。
创建一个geom_text_npc图层:
npc_txt = geom_text_npc(aes(npcx = 0.9, npcy = 0.1, label = "some text"), size = 6)
Run Code Online (Sandbox Code Playgroud)
...然后可以添加到所有地块:
ggplot(mpg) +
geom_point(aes(displ, hwy)) +
npc_txt
Run Code Online (Sandbox Code Playgroud)
ggplot(iris) +
geom_point(aes(Petal.Width, Petal.Length)) +
npc_txt
Run Code Online (Sandbox Code Playgroud)
如果您不需要数值npcx和npcy提供的坐标的精度,您还可以使用“单词”指定一些基本位置(角和中心)(请参阅通过关键字如“top”、“bottom”、“左”、“右”、“中”)。在您的示例中,与您的数字位置最相符的单词是"right"和"bottom":
npc_txt = geom_text_npc(aes(npcx = "right", npcy = "bottom", label = "some text"), size = 6)
ggplot(mpg) +
geom_point(aes(displ, hwy)) +
npc_txt
Run Code Online (Sandbox Code Playgroud)
ggplot(iris) +
geom_point(aes(Petal.Width, Petal.Length)) +
npc_txt
Run Code Online (Sandbox Code Playgroud)