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)
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)+
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?
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)
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