我正在使用ggplot2包在R中制作一个简单的条形图。我不想使用灰色默认值,而是将背景划分为五个区域,每个区域都有不同的(但同样低调的)颜色。我该怎么做?
更具体地说,我希望五个彩色区域的范围为0-25,25-45,45-65,65-85和85-100,其中颜色代表比铜更差,青铜色,银色,分别是黄金和白金。对配色方案的建议也非常受欢迎。
答案 0 :(得分:41)
这是一个让你入门的例子:
#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))
答案 1 :(得分: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"))
产生这个,
查看this site的配色方案建议。
答案 2 :(得分:0)