如何在为点着色时将文本添加到多面图?

How to add text to facceted plot while colouring the points?

我正在尝试向多面图添加文本,我可以使用

datasets_text <- data.frame(cyl = unique(mtcars$cyl))
datasets_text$label <- c('text1','text2','text3')

mtcars <- head(mtcars)
ggplot(mtcars, aes(hp,drat))+
  geom_point()+
  facet_wrap(~cyl)+
  geom_text(size    = 2,
          data    = datasets_text,
          mapping = aes(x = Inf, y = Inf, label = label),
          hjust   = 1.05,
          vjust   = 1.5)

而且我还想给可以用

做的点上色
mtcars <- head(mtcars)
ggplot(mtcars, aes(hp,drat, colour=gear))+
  geom_point()+
  facet_wrap(~cyl)+

然而,当我把两者结合起来时

ggplot(mtcars, aes(hp,drat, colour=gear))+
  geom_point()+
  facet_wrap(~cyl)+
  geom_text(size    = 2,
          data    = datasets_text,
          mapping = aes(x = Inf, y = Inf, label = label),
          hjust   = 1.05,
          vjust   = 1.5)

我得到 Error in FUN(X[[i]], ...) : object 'gear' not found。如何在为点着色的同时向构面添加文本?​​

您可以在对 geom_text 的调用中指定 inherit.aes = FALSE:

ggplot(mtcars, aes(hp,drat, colour=gear))+
    geom_point()+
    facet_wrap(~cyl)+
    geom_text(size    = 2,
              data    = datasets_text,
              mapping = aes(x = Inf, y = Inf, label = label),
              hjust   = 1.05,
              vjust   = 1.5, inherit.aes = FALSE)

来自 the geom_text help file 关于 inherit.aes:

If FALSE, overrides the default aesthetics, rather than combining with them. This is most useful for helper functions that define both data and aesthetics and shouldn't inherit behaviour from the default plot specification