简体   繁体   English

在 R 中使用 ggplot 在两个元素之间插入网格

[英]Insert a grid between two elements with ggplot in R

I am trying to overlay the background of my plot with a color depending on the x-axis, with geom_rect.我正在尝试使用 geom_rect 覆盖我的 plot 的背景,颜色取决于 x 轴。 For example, for x-values between 0.5 and 1.5, background will be grey.例如,对于介于 0.5 和 1.5 之间的 x 值,背景将为灰色。 It will be white for x-values between 1.5 and 2.5, then grey, etc. I also have a grid and boxplots on my plot.对于 1.5 和 2.5 之间的 x 值,它将是白色,然后是灰色等。我的 plot 上还有一个网格和箱线图。

I want for the grid to be ontop of this colored background but behind the boxplots.我希望网格位于此彩色背景之上,但位于箱线图之后。

p <- (p
      + theme_bw()
      + ggtitle(dates[i])
      + xlab("Echeance")
      + geom_rect(xmin=0.5, xmax=1.5, ymin=500, ymax=7500, fill="gray90")
      + geom_rect(xmin=1.5, xmax=2.5, ymin=500, ymax=7500, fill="gray100")
      + geom_rect(xmin=2.5, xmax=3.5, ymin=500, ymax=7500, fill="gray90")
      
      + geom_line(data=data, aes(x=Var3, y=value), group=1)
      + geom_boxplot(aes(linetype=exp))
      + guides(linetype="none")
      + scale_y_continuous(n.breaks = 20))

Without options, I have the colored background ontop of the grid, and behind the boxplots.没有选项,我在网格顶部和箱线图后面有彩色背景。

在此处输入图像描述

If I add如果我添加

 + theme(panel.ontop = TRUE, panel.background = element_rect(fill = NA))

Then I have the grid ontop the colored background but also on top of the boxplot...然后我将网格放在彩色背景之上,但也在箱线图之上......

在此处输入图像描述

Does someone has the trick?有人有诀窍吗?

Use (instead of geom_rect)使用(而不是 geom_rect)

+ annotate("rect", xmin=2.5, xmax=3.5, ymin = -Inf, ymax = Inf, fill="gray20", alpha = 0.2)

with alpha controling the transparency用 alpha 控制透明度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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