在R中使用ggplot2,我如何在不同区域使graphics的背景变成不同的颜色?

我使用ggplot2软件包在R中制作一个简单的条形图。 我不想将灰色的默认值分成五个区域,每个区域都是不同的(但是同样是低调的)颜色。 我如何做到这一点?

更具体地说,我想要五个颜色区域从0-25,25-45,45-65,65-85和85-100运行,其中颜色代表劣于青铜,青铜,银,金和铂分别。 一个配色scheme的build议也非常欢迎。

感谢您的帮助。

下面是一个启动的例子:

 #Fake data dat <- data.frame(x = 1:100, y = cumsum(rnorm(100))) #Breaks for background rectangles rects <- data.frame(xstart = seq(0,80,20), xend = seq(20,100,20), col = letters[1:5]) #As Baptiste points out, the order of the geom's matters, so putting your data as last will #make sure that it is plotted "on top" of the background rectangles. Updated code, but #did not update the JPEG...I think you'll get the point. ggplot() + geom_rect(data = rects, aes(xmin = xstart, xmax = xend, ymin = -Inf, ymax = Inf, fill = col), alpha = 0.4) + geom_line(data = dat, aes(x,y)) 

在这里输入图像描述

我想要移动直线或直方图的条纹到前景,如上面baptiste所build议的,并用+ theme(panel.background = element_rect(), panel.grid.major = element_line( colour = "white") ) ,不幸的是,我只能通过发送geom_bar两次,希望有人可以改善代码,并使答案完成。

 background <- data.frame(lower = seq( 0 , 3 , 1.5 ), upper = seq( 1.5, 4.5, 1.5 ), col = letters[1:3]) ggplot() + geom_bar( data = mtcars , aes( factor(cyl) ) ) + geom_rect( data = background , mapping = aes( xmin = lower , xmax = upper , ymin = 0 , ymax = 14 , fill = col ) , alpha = .5 ) + geom_bar(data = mtcars, aes(factor(cyl))) + theme(panel.background = element_rect(), panel.grid.major = element_line( colour = "white")) 

产生这个, geom_bar和geom_rect

看看这个网站的配色scheme的build议。