我对仅在功能区附近仅包含面板网格线的方法感兴趣-在一个简单的示例中,我可以手动执行此操作

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


r - ggplot2中的透明蒙版-LMLPHP

为这些网格线设置透明蒙版是否有一些别有用心的方法,因此它们仅出现在功能区下方?

最佳答案

如果可以接受与背景颜色相同的网格线,则可以删除实际的网格线,然后使用geom_hline()geom_vline()制作自己的“网格线”,它们将显示在功能区上,但在背景上不可见

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


产生这个:
r - ggplot2中的透明蒙版-LMLPHP

这仍然是一种解决方法,只会使网格线与背景色匹配,但是可以轻松地用于各种绘图,例如您提到的多个功能区的情况(我添加了第二个功能区来演示将工作)

10-04 12:09