giac
giac

Reputation: 4299

R geom_ribbon after specific value

I am trying to find a way to colour the background after a specific value.

Here in this example, I want to colour the spaces after the value 5 (here shown with a vertical line).

#

library(lme4)
library(tidyverse)
data("sleepstudy")

#
sleepstudy = sleepstudy %>% mutate(days = ifelse(Days > 5, 1, 0))
#

m1 = sleepstudy %>% group_by(Days, days) %>% summarise(m = mean(Reaction)) 
m1

m1 %>% ggplot(aes(Days, m)) + 
  geom_point() + 
  geom_vline(xintercept = 6) + 
  theme_minimal()

enter image description here

I want to achieve something like this

enter image description here

However, when I use the following line, I get an error message.

m1 %>% ggplot(aes(Days, m)) + 
  geom_point() + 
  geom_vline(xintercept = 6) + 
  theme_minimal() + 
  geom_ribbon(data = m1, aes(x = c(6,9), ymin=0, ymax = 400), fill = 'khaki', alpha = 0.2) 

Upvotes: 0

Views: 505

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

Maybe the following does what the question asks for.

First of all, if the error bars are to be plotted, the data preparation code must change.

  1. There is no need to compute an extra variable, days that tells if Days are greater than 6.
  2. The standard errors must be computed.

This can be all done in one pipe only.

library(lme4)
library(tidyverse)
data("sleepstudy")

m1 <- sleepstudy %>% 
  group_by(Days) %>% 
  summarise(m = mean(Reaction),
            s = sd(Reaction)) 

Now the plot.

  1. I have changed the order of the geoms, to have the points, error bars and vertical line over the ribbon.
  2. I have also increased the alpha level to 0.30.
  3. There is no need to reset the x aesthetic, it is set since the beginning of the plot.

It's the latter point that caused the code error.

Error: Aesthetics must be either length 1 or the same as the data (10): x

m1 %>% ggplot(aes(Days, m)) + 
  theme_minimal() + 
  geom_ribbon(data = m1 %>% filter(Days > 5), 
              aes(ymin = 0, ymax = 400), 
              fill = 'khaki', 
              alpha = 0.30) +
  geom_vline(xintercept = 6) + 
  geom_point() +
  geom_errorbar(aes(ymin = m - s, ymax = m + s))

enter image description here

Upvotes: 1

Related Questions