Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shade part of an R plot

Tags:

plot

r

I am trying to make a plot in R that has a portion of the plot grey to emphasize this area. Unlike other examples, I don't want to color an area under a plot, but instead color an area on a plot starting at one area and going to the end of the graph. When I try to use rect() or polygon() it obscures the plots I want to emphasize.

For example:

x_mean <- c(1, 2, 3, 4)
y_mean <- c(1, 1, 1, 1)

y_max <- c(4, 4, 4, 4)
y_min <- c(-4, -4, -4, -4)


x_shade <- c(2, 3, 4)

y_max_shade <- c(4, 4, 4)
y_min_shade <- c(-4, -4, -4)

plot(x=rep(x_mean, 3), y=c(y_mean, y_max, y_min), bty='n', type="n" )
arrows(x0=x_mean, y0=y_min, x1=x_mean, y1=y_max, length=0)
points( x=x_mean, y=y_mean, pch=16)

This will plot 4 lines on the graph. How do I draw a grey box in the background from the 2nd line to the end of the plot?

like image 518
Kevin Avatar asked Jun 28 '12 17:06

Kevin


People also ask

How do I shade an area under a graph in R?

The polygon function can be used to shade the area under the density curve. You just need to pass the density object to it and specify a color.

How do you shade a graph in R?

Method 1: Shade a graph using polygon function : In this method, we are calling the polygon function with its argument col passed with the name or the hex code of the color needed to be shaded in the given graph.

How do I change the color of my plot points in R?

Change R base plot point shapes To change the color and the size of points, use the following arguments: col : color (hexadecimal color code or color name). For example, col = "blue" or col = "#4F6228" .

How do you shade a normal distribution curve in R?

The easiest-to-find method for shading under a normal density is to use the polygon() command. That link is to the first hit on Google for “Shading Under a Normal Curve in R.” It works (like a charm), but it is not the most intuitive way to let users produce plots of normal densities.


1 Answers

Just so that you're left with more than just a comment, here's a possible solution:

plot(x=rep(x_mean, 3), y=c(y_mean, y_max, y_min), bty='n', type="n" )
rect(2,-4,4,4,col = rgb(0.5,0.5,0.5,1/4))
arrows(x0=x_mean, y0=y_min, x1=x_mean, y1=y_max, length=0)
points( x=x_mean, y=y_mean, pch=16)

enter image description here

Note that I also demonstrated how to use alpha blending in the color specification (using rgb). This can also be useful for this sort of thing. Try moving the rect line to the end, and notice that the results still look ok, because the fill color is partially transparent.

like image 110
joran Avatar answered Sep 20 '22 06:09

joran