user111024
user111024

Reputation: 811

Alternating rectangles in ggplot

What's the best way of getting something like the example below in ggplot? Is it geom_tile? geom_raster? geom_area? geom_ribbon?

yValsOdd <- seq(1,10,2)
yValsEven <- seq(2,10,2)
xMin <- 0
xMax <- 10

plot(x = c(xMin,xMax), y=c(0,10), type = "n",
     axes = FALSE)
rect(xleft = xMin, ybottom = yValsOdd - 0.5, xright = xMax, ytop = yValsOdd + 0.5, 
     col = "grey90", border = NA)
rect(xleft = xMin, ybottom = yValsEven - 0.5, xright = xMax, ytop = yValsEven + 0.5, 
     col = "lightblue", border = NA)

enter image description here

Upvotes: 0

Views: 79

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145775

I'd use geom_tile:

d = data.frame(y = 1:10)
d$ev = factor(d$y %% 2)
ggplot() +
  geom_tile(
    data = d,
    aes(x = 0, y = y - 0.5, fill = ev),
    width = Inf, height = 1,
    show.legend = FALSE
  ) +
  scale_fill_manual(values = c("grey90", "lightblue")) +
  theme_minimal()```

enter image description here

You'll need to make sure whatever x aesthetic you set on the geom_tile layer is within the x range you want plot, but after that the x axis should scale automatically to whatever other data is present.

Upvotes: 1

Related Questions