我正在使用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)
由于您要突出显示垂直(或水平)区域,因此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)
我想按照上面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)
产生这个
看看这个网站上的配色方案建议。