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')
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.
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.
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With