Adding grey shaded area in ggplot2

I've recently started to work with ggplot2 and R in general. I'm working on a plot I would like to use for presentation purposes, but I have some difficulty cleaning it properly.

Specifically, I would like the grey shaded rectangle to go all the way from top to bottom. I need to specify -ymin- and -ymax-, but it does not alter the rectangle the way I want. Hopefully, someone here can help me out.

Don't mind the time variable, it's originally Stata-formatted and I'm currently working on importing Stata-formatted date variables to R. (I would appreciate sources on this as well.)

GP_treatment <- ggplot(GP_intervention_data_viz, 
       aes(x = monthly_date, y = suiciderate, col = factor(intervention))) + 
  geom_smooth(se = FALSE) +
  annotate("rect", xmin = 672, xmax = 695, ymin = 0.5, ymax = 1, 
           alpha = .5)

val = c("#E41A1C", "#377EB8")
lab = c("Control", "Treatment")  

GP_treatment +
  scale_x_continuous("Month") + 
  scale_y_continuous("Monthly suicide rate per 100 000") +
  scale_color_manual("Treatment status", 
                    values = val,
                    labels = lab)

And here is the plot. As you can see, some additional space above 1.5 and below 0.5 is automatically added, and I would like to remove this:

Add expand = c(0,0) to your y scale

scale_y_continuous("Monthly suicide rate per 100 000", expand = c(0,0))


Great, thank your very much!

If your question has been answered, would you mind choosing a solution? (see FAQ below for how) It makes it a bit easier to visually navigate the site and see which questions still need help.


1 Like

Of course, thank you for the heads up! I'll check out the FAQ

You can also use Inf and -Inf to make the rect goes spans the whole y-axis, regardless of the scales and limits.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.