3

I'm interested in ways to only include panel grid lines right near the ribbon--I can do this manually, in a trivial example

library(ggplot2)

d1 <- data.frame(x = seq(0, 1, length.out = 200))
d1$y1 <- -3*(d1$x-.5)^2 + 1
d1$y2 <- -3*(d1$x-.5)^2 + 2

ggplot(d1) +
 geom_ribbon(aes(x, ymin = y1, ymax = y2),
             alpha = .25) +
 geom_ribbon(aes(x, ymax = y1),
             ymin = .25, 
             fill = "white") +
 geom_ribbon(aes(x, ymin = y2),
            ymax = 2, 
            fill = "white") +
 scale_y_continuous(limits = c(.25, 2.0),
                    expand = c(0, 0))+
scale_x_continuous(limits = c(0, 1),
                   expand = c(0, 0))+
theme_bw() +
theme(panel.grid = element_line(linetype = 1, color = "black")) 

example of clipping

is there some less hacky way to have a transparent mask for these gridlines, so they only appear underneath a ribbon?

tomw
  • 3,114
  • 4
  • 29
  • 51
  • I have seen worse codes, please make clear what you mean by less hacky? Not masking them with a white ribbon, is that it? – RHA Sep 05 '15 at 07:46
  • No, I meant with a less trivial example: for instance when you have multiple ribbons with varying regions of overlap, I wouldn't be able to neatly pass these blocking ribbons. Is there no grid code which allows windows of transparency through a layer underneath (for example)? – tomw Sep 05 '15 at 14:54
  • Hmm, difficult. You might try to create a polygon and fill it with a grid pattern like [here](http://stackoverflow.com/questions/26110160/how-to-apply-cross-hatching-to-a-polygon-using-the-grid-graphical-system) – RHA Sep 06 '15 at 21:09

1 Answers1

1

If gridlines the same color as the background are acceptable, you can remove the actual gridlines, then use geom_hline() and geom_vline() to make your own "gridlines" that will show on ribbons but be invisible against the background

d1$y3 <- d1$x + 0.3
d1$y4 <- d1$x + 0.4

ggplot(d1) +
  geom_ribbon(aes(x, ymin = y1, ymax = y2), alpha = 0.25) +
  geom_ribbon(aes(x, ymin = y3, ymax = y4), alpha = 0.25, fill = "blue") +
  # use geom_vline and geom_hline to plot "gridlines" on top of ribbons
  geom_hline(yintercept = seq(0, 2, by = 0.25), colour = "white") +
  geom_vline(xintercept = seq(0, 1, by = 0.25), colour = "white") +
  scale_y_continuous(limits = c(.25, 2.0), expand = c(0, 0)) +
  scale_x_continuous(limits = c(0, 1), expand = c(0, 0)) +
  theme_bw() +
  theme(panel.grid.minor = element_blank(), # remove actual gridlines
        panel.grid.major = element_blank())

produces this: enter image description here

This is still a workaround, and will only make gridlines that match the background color, but it is easy to use with a variety of plots, such as the situation you mentioned with multiple ribbons (I've added a second ribbon to demonstrate that this will work)

Jan Boyer
  • 1,540
  • 2
  • 14
  • 22