Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

r - Draw a box around some of the plots when using `facet_wrap` in ggplot2

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!

question from:https://stackoverflow.com/questions/65925143/draw-a-box-around-some-of-the-plots-when-using-facet-wrap-in-ggplot2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...