仅在 ggplot 的一个方面创建自定义注释

creating custom annotations in only one facet of a ggplot

有没有办法指定 custom_annotation 仅适用于 ggplot 的一个方面?

例如,如果我运行下面的代码

library(tidyverse)
library(grid)

text_grob=grobTree(textGrob("text",x=0.5, y=0.6, rot=90,
    gp=gpar(col="red")))

ggplot(mtcars, aes(x=mpg, y =drat))+
  geom_point() +
  facet_wrap(~cyl) +
  annotation_custom(overrep_grob)

我明白了

如何只保留最右边的红色"text"注解,而不在前两个切面添加"text"注解?注意我不能使用 geom_textannotate 因为我需要使用 textGrob 的相对文本定位

egggeom_custom,

library(ggplot2)
library(grid)
library(egg)

d = data.frame(cyl=6, drat = 4, mpg = 15)
d$grob <- list(textGrob("text",rot=90, hjust = 0, gp=gpar(col="red")))

ggplot(mtcars, aes(x=mpg, y=drat))+
  geom_point() +
  facet_wrap(~cyl) +
  geom_custom(data = d, aes(data = grob), grob_fun = identity)

您也可以使用 geom_text 通过计算所需文本的相对位置来执行此操作。请注意,此处的相对位置与您上面使用的略有不同,因为此处我将相对位置定义为动态范围的某个比例。您可以为 rel 选择不同的值以获得您需要的位置。我发现这种方式使定位不那么随意。

library(tidyverse)

rel_pos <- function(.data, var, rel){
  var <- enquo(var)
  .data %>% 
    summarise(x = sum(max(!!var), min(!!var))* rel) %>% .[1, "x"]
}

my_text <- data_frame(mpg = rel_pos(mtcars, mpg, 0.5), 
                      drat = rel_pos(mtcars, drat, 0.6) , 
                      cyl = 8, lab = "text")

ggplot(mtcars, aes(x=mpg, y =drat))+
  geom_point() +
  facet_wrap(~cyl)+
  geom_text(data = my_text, aes(label = lab), color = "red", angle = 90)

reprex 创建于 2018-08-15 包 (v0.2.0).