6

I would like to fill the area above and below the two horizontal lines.

This is what I have come up with:

Plot

 par(mfrow=c(1,2))
 x<-seq(1,24,1)
 y<-rnorm(24, 10, 2)

 for(i in 1:2) {
 plot(x,y,ylim=c(4,16))
 lines(x,y)
 abline(h=11)
 abline(h=9)}

 hyper<-y
 hyper[hyper<11]<-11
 polygon(x,hyper,col="gray")

My main problem is that the intersect with the horizontal line is not right.

Lafexlos
  • 7,618
  • 5
  • 38
  • 53
moabit21
  • 639
  • 8
  • 20
  • 2
    Your main problem is that you need to get the intersections between the horizontal lines and the lines going above / below. The x-values there are what you need. This will involve a little bit of calculation. Also, keep in mind that you can make separate complete polygons with NA values in the vector. Although, once you solve this you might find the simplest way is to make individual polygons for each point above / below. – John May 17 '14 at 16:39
  • Have a look at [**this answer**](http://stackoverflow.com/questions/9973381/shading-an-area-between-geom-line-and-the-x-axis/9974544#9974544). Shouldn't be to hard to adapt it to your needs. – Henrik May 17 '14 at 18:49
  • I thought @gagolews answer was much more elegant. I suspect that there may be an effective strategy in the spatial plotting functions as well since they allow calculations of intersections, but am too lazy to try it. – IRTFM May 18 '14 at 15:17

1 Answers1

12

If you still wish to make the figure with the old-school graphics facilities (plot, abline, lines, and so on - the other suggestions concern the grid system derivatives, like ggplot2), you may try to play with a custom clipping region, see ?clip:

an illustration

par(mfrow=c(1, 2))
x <- seq(1, 24, 1)
y <- rnorm(24, 10, 2)

# 1st plot
plot(x, y, ylim=c(4,16), type='o')

# 2nd plot
plot(x, y, type='n', ylim=c(4,16))

clip(x1=min(x),x2=max(x), y1=11, y2=max(y))
polygon(c(min(x), x, max(x)), c(min(y), y, min(y)), col="gray")

clip(x1=min(x),x2=max(x), y1=9, y2=min(y))
polygon(c(min(x), x, max(x)), c(max(y), y, max(y)), col="gray")

clip(par("usr")[1], par("usr")[2], par("usr")[3], par("usr")[4]) # reset clipping region
lines(x,y, type='o')
abline(h=c(9, 11))

First we set up the plot region with no plotting, then we set up two different clipping regions (into which we plot with grey fills), then we remove the clipping region and re-did plotting with lines and points.

gagolews
  • 12,836
  • 2
  • 50
  • 75