0

I have a kind of "time series", with different measures taken at regular points on the same individuals. I want to graphically represent 2 of these time series on the same graph (no problem with that), and add a background which depends on a third factor.

Here a reproducible example of what I've done:

df <- data.frame(
  x = seq(1, 20),
  y = sample(c(1:10), 20, replace = TRUE),
  z = sample(c(1:10), 20, replace = TRUE),
  w = sample(c("yes", "no"), 20, replace = TRUE)
)

ggplot(df) +
  geom_line(aes(x = x, y = y), color = 'darkorange') +
  geom_line(aes(x = x, y = z), color = 'royalblue') +
  geom_raster(aes(x = x, y = 5, fill = w, alpha = w)) +
  scale_alpha_ordinal(range = c(0, 0.8)) +
  scale_fill_manual(values = c("gray32", "gray32"))

Which give me almost what I want excepted that I would like my raster to cover my whole y-axis window.

Any idea?

Thank you!

moyneo
  • 1

1 Answers1

0

I think it's simplest to use geom_rect here:

ggplot(df) +
  geom_line(aes(x = x, y = y), color = 'darkorange') +
  geom_line(aes(x = x, y = z), color = 'royalblue') +
  geom_rect(aes(xmin = x - 0.5, xmax = x + 0.5, 
                ymin = -Inf, ymax = Inf, fill = w, alpha = w)) +
  scale_alpha_ordinal(range = c(0, 0.8)) +
  scale_fill_manual(values = c("gray32", "gray32"))

enter image description here

It's probably also possible with geom_tile and geom_raster, but I couldn't get the range to cover the whole vertical space without also fiddling with coord_cartesian.

Jon Spring
  • 55,165
  • 4
  • 35
  • 53