Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change background color on just one region of the graph [duplicate]

I would like to change the background color for just a portion of a graph. Is that possible?

For example, using the following chart I might want to indicate that I am particularly interested in cars that have a weight between 2 and 4 tons and thus would want to highlight this region using a pink background.

More specifically I'd like to overlay a transparent pink rectangle which stretches from 2 to 4 on the x axis and covers the entire y axis region.

How would I code this?

p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
like image 203
Megan Avatar asked Jan 07 '14 19:01

Megan


People also ask

How do you change the background color of a plot in Matlab?

a) From the File menu, select "Export setup". b) Under Properties select Rendering and check the “Custom color” option. c) Enter “w” in the adjacent text box and click “Apply to Figure” to update the figure. d) Use the “Edit -> copy figure” option to copy and paste the figure with white background in PowerPoint.


2 Answers

The rectangle is easy using geom_rect (documentation). You just need to specify it's dimensions in the aes call to geom_rect. To change the transparency alter alpha in the code below.

 require(ggplot2)
 p <- ggplot(mtcars, aes(wt, mpg)) 
 p + geom_point() + 
     geom_rect(aes(xmin = 2, xmax = 4, ymin = -Inf, ymax = Inf),
                   fill = "pink", alpha = 0.03))

Does that produce something like what you're after?

Figure attempt

like image 105
Adam Kimberley Avatar answered Sep 29 '22 16:09

Adam Kimberley


Although this works, I noticed that it plots as many rectangles as data points, which might be a problem especially with facetting where the number of points changes between facets. This is reflected by a very low alpha to obtain just approx 50% transparency. I think it's because it uses the data.frame and aesthetics called from ggplot().

One way to avoid that could be calling aes() within geom_point() and create a data.frame specifically for the rectangles. Notice how alpha is much larger but the effect is similar.

require(ggplot2)
ggplot(mtcars) + geom_point(aes(wt, mpg)) + 
geom_rect(data=data.frame(xmin = 2, xmax = 4, ymin = -Inf, ymax = Inf),
    aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax), fill="pink", alpha=0.5)

Result enter image description here

like image 38
abreschi Avatar answered Sep 29 '22 18:09

abreschi