Make the background of a graph different colours i

2020-01-22 13:18发布

I'm making a straightforward barchart in R using the ggplot2 package. Rather than the grey default I'd like to divide the background into five regions, each a different (but similarly understated) colour. How do I do this?

More specifically, I'd like the five coloured regions to run from 0-25, 25-45, 45-65, 65-85 and 85-100 where the colours represent worse-than-bronze, bronze, silver, gold and platinum respectively. Suggestions for a colour scheme very welcome too.

标签: r ggplot2
2条回答
三岁会撩人
2楼-- · 2020-01-22 13:44

I wanted to move the line⎯or the bars of the histogram⎯to the foreground, as suggested by baptiste above and fix the background with + theme(panel.background = element_rect(), panel.grid.major = element_line( colour = "white") ), unfortunately I could only do it by sending the geom_bar twice, hopefully someone can improve the code and make the answer complete.

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"))

Produces this, geom_bar and geom_rect

Take a look at this site for colour scheme suggestions.

查看更多
三岁会撩人
3楼-- · 2020-01-22 13:56

Here's an example to get you started:

#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))

enter image description here

查看更多
登录 后发表回答