0

I created the following plot with panels using ggplot():

ggplot(merged.table, aes(x=iter, y=freq,group=var)) + geom_line()+facet_wrap(.~var)

enter image description here

I would like to draw a box around some plots whose number is identified in a vector trueplots:

trueplots<-sample(1:25,5)

I followed the procedure here and tried

ggplot(merged.table, mapping=aes(x=iter, y=freq,group=var)) + geom_line()+geom_rect(subset(merged.table, var %in% trueplots),fill = NA, colour = "red", )+facet_wrap(.~var)

and

ggplot(merged.table, mapping=aes(x=iter, y=freq,group=var)) + geom_line()+geom_rect(subset(merged.table, var %in% trueplots),fill = NA, colour = "red", xmin= -Inf,xmax = Inf,ymin = -Inf,ymax = Inf)+facet_wrap(.~var)

but I get the error

Error: `mapping` must be created by `aes()`

Any hint? Thank you!

coolsv
  • 781
  • 5
  • 16

1 Answers1

1

I think you simply forgot to put the mapping inside aes() and it seems to be in the wrong position in geom_rect() argument list (mapping is the first argument, not data).

Example with a standard dataset:

library(ggplot2)

df <- mtcars
df$facet <- interaction(df$cyl, df$carb, drop = TRUE)

trueplots <- sample(levels(df$facet), 5)

ggplot(df, aes(disp, hp)) +
  geom_point() + 
  geom_rect(aes(xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf),
            data = ~ subset(., facet %in% trueplots), 
            colour = "black", fill = NA, inherit.aes = FALSE) +
  facet_wrap(~ facet)

Created on 2021-01-27 by the reprex package (v0.3.0)

teunbrand
  • 33,645
  • 4
  • 37
  • 63