Search code examples
rggplot2facetfacet-wrap

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


I am trying to add text to facetted plot which I can do with

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)

enter image description here

And I also want to colour the points which I can do with

mtcars <- head(mtcars)
ggplot(mtcars, aes(hp,drat, colour=gear))+
  geom_point()+
  facet_wrap(~cyl)+

enter image description here

However, when I combine the two

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)

I get Error in FUN(X[[i]], ...) : object 'gear' not found. How can I add text to the facets while also coloring the points?


Solution

  • You can specify inherit.aes = FALSE in the call to geom_text:

    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)
    

    enter image description here

    From the geom_text help file regarding 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