This question is a follow-up to: Annotating text on individual facet in ggplot2
I was trying out the code provided in the accepted answer and got something that was strangely different than the result provided. Granted the post is older and I'm using R 3.5.3 and ggplot2 3.1.0, but what I'm getting doesn't seem to make sense.
library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <- p + facet_grid(. ~ cyl)
#below is how the original post created a dataframe for the text annotation
#this will produce an extra facet in the plot for reasons I don't know
ann_text <- data.frame(mpg = 15,wt = 5,lab = "Text",cyl = factor(8,levels = c("4","6","8")))
p+geom_text(data = ann_text,label = "Text")
This is the code from the accepted answer in the linked question. For me it produces the following graph with an extra facet (i.e, an addition categorical variable of 3 seems to have been added to cyl)
#below is an alternative version that produces the correct plot, that is,
#without any extra facets.
ann_text_alternate <- data.frame(mpg = 15,wt = 5,lab = "Text",cyl = 8)
p+geom_text(data = ann_text_alternate,label = "Text")
This gives me the correct graph:
Anybody have any explanations?
str(ann_text)
The last row of the output is$ cyl: Factor w/ 3 levels "4","6","8": 3
. So the level"8"
is code as the number3
. Since you facet bycyl
you have one more value. Another solution isfacet_grid(. ~ factor(cyl))
. – Rui Barradas