简体   繁体   中英

Transparent masking in ggplot2

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")) 

剪辑的例子

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

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: 在此输入图像描述

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM