Reputation: 1400
Using the mpg
data from ggplot2
package I want to apply facet_wrap()
preserving the statistical symbols added with annotate()
:
ggplot(mpg[ mpg$drv == levels(mpg$drv)[1] ,],
aes(x = class, y = hwy)) +
geom_boxplot() +
annotate("segment", x=2, xend=3, y= 26, yend = 26) +
annotate("text", x=2.5, y= 27, label = "*", size = 10)
ggplot(mpg[ mpg$drv == levels(mpg$drv)[2] ,],
aes(x = class, y = hwy)) +
geom_boxplot() +
annotate("segment", x=3, xend=4, y= 45, yend = 45) +
annotate("text", x=3.5, y= 46, label = "*", size = 10)
I have tried storing each plot as an object and the adding it to an empty facet. It is the only think I could come up with and it didn't work:
ggplot(mpg, aes(x = class, y = hwy)) +
facet_wrap( ~ drv) +
plot1 + plot2
Error in p + o : non-numeric argument to binary operator
In addition: Warning message:
Incompatible methods ("+.gg", "Ops.data.frame") for "+"
your help is greatly appreciated, Sergio
Upvotes: 0
Views: 88
Reputation: 5530
Rather than use annotate, the geom_text and geom_segment functions can be used which allow text and segments to be mapped to other variables and so have different values in different facet panels. The example code could look like:
annote <- data.frame(x_cls = c(2.5, 3.5, 4.5), x_cls_end=c(3, 4, 5), y_hwy= c(26, 45, 55), y_hwy_end= c(26, 45, 55), drv = c("4", "f", "r") )
ggplot(mpg, aes(x = class, y = hwy)) +
geom_boxplot() +
geom_segment(data=annote, aes(x=x_cls, xend = x_cls_end, y= y_hwy, yend=y_hwy_end) ) +
geom_text(data=annote, aes(x=x_cls, y= y_hwy, label = "*"), size = 10) +
facet_wrap( ~ drv)
Upvotes: 1