Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shading area between two lines in r

Tags:

plot

r

For example if i need to shade two area in plot

x<-rep(1:10)
plot(x,type="h")

I need as an example shade the area from 1 to 3 and from 7 to 10,

I use this commands but it omitted the lines of plot.

usr <- par('usr')
rect(1, usr[3], 3, usr[4], col='green')
like image 876
user3478697 Avatar asked Apr 28 '14 21:04

user3478697


People also ask

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.

What are R lines?

lines() function in R Programming Language is used to add lines of different types, colors and width to an existing plot. Syntax: lines(x, y, col, lwd, lty) Parameters: x, y: Vector of coordinates. col: Color of line.


2 Answers

If I understand you correctly, you can get what you want by using the little-known panel.first= argument to plot.default():

plot(x,type="h", 
     panel.first = {
         usr <- par('usr')
         rect(c(1,7), usr[3], c(3,10), usr[4], col='green', border=NA)
     })

Or, to avoid any mucking around with par('usr') values, just do:

plot(x, type="h", 
     panel.first = rect(c(1,7), -1e6, c(3,10), 1e6, col='green', border=NA))

enter image description here

like image 133
Josh O'Brien Avatar answered Sep 29 '22 19:09

Josh O'Brien


See ?polygon:

polygon( x = c(1,1,3,3,1), y=c( usr[1], x[1], x[3], usr[1], usr[1]) ,col="red")

> polygon( x = c(1,1,3,3,1), y=c( usr[1], x[1], x[3], usr[1], usr[1]) ,col="red")
> polygon( x = c(7,7,10,10,7), y=c( usr[2], x[7], x[10], usr[1], usr[1]) ,col="red")

I chose to close the polygon but seem I remember you can get it to self-close.

enter image description here

like image 26
IRTFM Avatar answered Sep 29 '22 18:09

IRTFM