user1723765
user1723765

Reputation: 6399

Add shading to R base plot

I have a simple plot:

x1<- sort(rnorm(100))
x_max <- x1-0.5
x_min <- x1+0.5

plot(x1,type='l')
points(x_max,type='l',col="red")
points(x_min,type='l',col="red")

I would like to add grey shading between the two red lines.

I am looking for a solution that uses the basic R plotting function of R and not ggplot.

Upvotes: 1

Views: 1576

Answers (1)

ekstroem
ekstroem

Reputation: 6181

You can try using polygon. If you set the color for the polygon with an alpha channel then things don't overwrite anything. Also adding the suggestion by @rawr to use panel.first.

x1 <- sort(rnorm(100))
x_max <- x1-0.5
x_min <- x1+0.5

plot(x1, type = 'l', panel.first = polygon(c(1:length(x1),length(x1):1), c(x_min, rev(x_max)), col="#eeeeeeaa", border = NA))
points(x_max,type='l',col="red")
points(x_min,type='l',col="red")

Upvotes: 5

Related Questions