首页 > 解决方案 > R GGPLOT2 Alternate panel.background 填充白色和灰色

问题描述

我想在 ggplot2 中创建一个线图,面板背景颜色根据 X 轴值在白色和灰色之间交替。

在这种情况下DOY是一年中的一天,我希望它在每一天之间转换。

我包含了一些基本的示例代码。基本上想要在DOY 1-2白色和DOY 2-3灰色之间等等。

任何帮助表示赞赏,在此先感谢。

DOY <- c(1, 2, 3, 4, 5)
Max <- c(200, 225, 250, 275, 300)
sample <- data.frame(DOY, Max)

ggplot()+
  geom_line(data=sample, aes(x=DOY, y=Max), color = "black")

标签: rggplot2

解决方案


解决此问题的一种方法是向数据中添加一个新变量(称为eg stripe),该变量根据 DOY 的值交替变化。然后,您可以使用该变量作为填充透明矩形的基础。

我假设这DOY是一个间隔 = 1 的整数序列,所以我们可以根据 DOY 是奇数还是偶数来分配。

(注意:sample- 不是一个很好的变量名,因为该名称有一个函数)。

library(dplyr)
library(ggplot2)

sample %>% 
  mutate(stripe = factor(ifelse(DOY %% 2 == 0, 1, 0))) %>% 
  ggplot(aes(DOY, Max)) + 
  geom_point() + 
  geom_rect(aes(xmax = DOY + 1, 
                xmin = DOY, 
                ymin = min(Max), 
                ymax = Inf, 
                fill = stripe), alpha = 0.4) + 
  scale_fill_manual(values = c("white", "grey50")) + 
  theme_bw() + 
  guides(fill = FALSE)

结果:

在此处输入图像描述


推荐阅读