2

I made a faceted graph using ggplot, and then tried to use the function annotate to create a grey highlighted area in one specific panel of the plot only.

I tried to adapt the labeling method from this question, but I couldn't get it to work: How to add annotation on each facet

Here is a reproducible example:

ggplot(iris, aes(x = Sepal.Length))+
      geom_point(aes(y = Petal.Length))+
      facet_grid(Species~.)+
      annotate(geom = 'rect', xmin = 6, xmax = 6.5, ymin= 0, ymax= Inf,
               fill = 'grey20', alpha = 0.2)

output:

enter image description here

I want the grey highlight to appear on only the versicolor facet, not every facet.

EDIT

As the user @user11362344 has proposed, i test his indication to use geom_rect(), and add to the code in the place of annotate() and WORKED VERY WELL!:

ggplot(data_2, aes(x = Sepal.Length))+
  geom_point(aes(y = Petal.Length))+
  facet_grid(Species~.)+
  geom_rect(data=data.frame(Species='versicolor'), inherit.aes=F, 
            xmin = 6, xmax = 6.5, ymin = 0, ymax = Inf, fill = 'grey20', alpha = 0.2)

output:

enter image description here

Thanks everyone for the help! And specially thanks for @user11362344!

1 Answers1

0
  geom_rect(data=data.frame(Species='versicolor'), inherit.aes=FALSE,
            xmin = 6, xmax = 6.5, ymin= 0, ymax= Inf,
            fill = 'grey20', alpha = 0.2)
  • 2
    Code-only answers are considered low-quality. Your answer is likely to be deleted if you don't edit it so as to add an explanation. – Nino Filiu Apr 15 '19 at 20:13