使图表的背景在不同区域中具有不同的颜色

Mat*_*lis 37 r ggplot2

我正在使用ggplot2包在R中制作一个简单的条形图.我不想使用灰色默认值,而是将背景划分为五个区域,每个区域都有不同的(但同样低调的)颜色.我该怎么做呢?

更具体地说,我希望五个颜色区域在0-25,25-45,45-65,65-85和85-100之间运行,其中颜色代表比青铜,青铜,银,金和铂更差的颜色分别.对配色方案的建议也非常受欢迎.

Cha*_*ase 48

这是一个让你入门的例子:

#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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 将线条放在线下可能会更好 (3认同)
  • 通过这些绘图,我想添加`scale_x_continuous(expand = c(0,0))+ scale_y_continuous(expand = c(0,0))`以消除矩形和轴之间的多余空间。我觉得它在美学上更令人愉悦。 (2认同)

dmi*_*kno 7

由于您要突出显示垂直(或水平)区域,因此geom_rect()可能会出现过冲。请考虑geom_ribbon()

ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_point() +
  geom_ribbon(aes(xmin=3, xmax=4.2), alpha=0.25) +
  theme_minimal()
Run Code Online (Sandbox Code Playgroud)

几何带

  • 尽管“geom_ribbon”隐式地从面板中的数据中获取“ymin”和“ymax”。如果您可能要使用多面演示,请注意,功能区将根据显示的值在每个面板中采用不同的高度。 (2认同)

Eri*_*ail 5

我想按照上面baptiste的建议将线(或直方图的条形图)移到前景,并使用来固定背景 + 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"))
Run Code Online (Sandbox Code Playgroud)

产生这个 geom_bar和geom_rect

看看这个网站上的配色方案建议。