Fill the area above and below the horizontal lines on the plot

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

Here is what I came 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 intersection with the horizontal line is wrong.

+6
source share
1 answer

If you still want to make a figure with the old school graphics ( plot , abline , lines , etc. - other sentences relate to system derivatives of the grid , for example ggplot2 ), you can try playing with a custom clipping environment, 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 adjust the plot area without plotting, then we set up two different clipping areas (in which we build the gray fill), then we delete the cut area and re-draw with the lines and points.

+12
source

Source: https://habr.com/ru/post/969438/


All Articles