r - 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")
解决方案
解决此问题的一种方法是向数据中添加一个新变量(称为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)
结果:
推荐阅读
- c# - 如何使用 C# 命名空间
- angular - Angular7路由重定向用户
- webpack - 如何在 webpack 中使用 Terser 插件保留空格和缩进?
- python - Python从另一个字符串列表中减去字符串列表
- python - Plotly:如何设置热图纵横比?
- angular - 找不到 'of'' Angular 的名称
- python - 无法将 python 从 3.7 降级到 3.6 或 3.5
- json - Check if JSON is Object or Array
- swift - Swift - UIPanGestureRecognizer 在只想选择顶层时选择所有层
- python - 如何测试用户输入的字符串是否在列表中?