Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make the background of a graph different colours in different regions

Tags:

r

ggplot2

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.

like image 393
Matt Ollis Avatar asked Apr 01 '12 20:04

Matt Ollis


People also ask

How do I change the background color on Origin?

The layer background color can be set independent of the page background color using controls available in the Background tab of the Plot Details dialog box at the Layer level, described below. Note that the layer background color is set to None by default.


2 Answers

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

like image 60
Chase Avatar answered Sep 22 '22 23:09

Chase


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.

like image 27
Eric Fail Avatar answered Sep 23 '22 23:09

Eric Fail