3

Goal: Plot a rectangle (geom_rect) that spans the plotting window.

Problem: Can't get ggplot2 to accept xlims.

Example:

library(lubridate)
library(ggplot2)

#Data frame
df <- data.frame(time=seq(ymd_hm('2016-01-26 08:00'),ymd_hm('2016-01-26 18:00'), length.out = 100), y=rnorm(100), facto=rep(c('a','b'), each=50))

#Call to ggplot
ggplot(df, aes(time, y))+
  geom_point()+
  facet_wrap(~facto)+
  geom_rect(aes(xmin=ymd_hm('2016-01-26 07:00'), xmax=ymd_hm('2016-01-26 20:00'), ymin=-1, ymax=1), fill='skyblue4', alpha=I(0.3), data=df[1,])

In plot below, the rectangle does not span the plotting window (desired outcome). The wider the rectangle, the wider the window, and the rectangle never reaches the sides.

enter image description here

Simple answer seems to be setting the xlims (How to set limits for axes in ggplot2 R plots?).

However, using xlim doesn't seem to take (arg is ignored), you can't use coord_cartesian with facets, and applying the scale_x_datetime yields unexpected results:

ggplot(df, aes(time, y))+
  geom_point()+
  facet_wrap(~facto)+
  geom_rect(aes(xmin=ymd_hm('2016-01-26 07:00'), xmax=ymd_hm('2016-01-26 20:00'), ymin=-1, ymax=1), fill='skyblue4', alpha=I(0.3), data=df[1,])+
  scale_x_datetime(limits = c(ymd_hm('2016-01-26 08:00'),ymd_hm('2016-01-26 19:00')))

Note how x-values are no longer accurately represented enter image description here

Further attempts: I've tried freeing the scales in the facet_wrap without effect. Also tried calls to xlim as a separate line and xlim within the call to ggplot, geom_point, and geom_rect.

Community
  • 1
  • 1
Minnow
  • 1,733
  • 2
  • 26
  • 52

1 Answers1

4
geom_rect(xmin = -Inf, xmax = Inf, ymin = -1, ymax = 1,
          fill = 'skyblue4', alpha = I(0.3), data = df[1, ])

solves the problem:

enter image description here

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102