Last active
August 29, 2015 14:10
-
-
Save johnbaums/ac50524427d3b0329936 to your computer and use it in GitHub Desktop.
Vertical gradient fill of area between a curve and zero.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
shade <- function(x, y, col, n=500, xlab='x', ylab='y', ...) { | |
# x, y: the x and y coordinates | |
# col: a vector of colours (hex, numeric, character), or a colorRampPalette | |
# n: the vertical resolution of the gradient | |
# ...: further args to plot() | |
plot(x, y, type='n', las=1, xlab=xlab, ylab=ylab, ...) | |
e <- par('usr') | |
height <- diff(e[3:4])/(n-1) | |
y_up <- seq(0, e[4], height) | |
y_down <- seq(0, e[3], -height) | |
ncolor <- max(length(y_up), length(y_down)) | |
pal <- if(!is.function(col)) colorRampPalette(col)(ncolor) else col(ncolor) | |
# plot rectangles to simulate colour gradient | |
sapply(seq_len(n), | |
function(i) { | |
rect(min(x), y_up[i], max(x), y_up[i] + height, col=pal[i], border=NA) | |
rect(min(x), y_down[i], max(x), y_down[i] - height, col=pal[i], border=NA) | |
}) | |
# plot white polygons representing the inverse of the area of interest | |
polygon(c(min(x), x, max(x), rev(x)), | |
c(e[4], ifelse(y > 0, y, 0), | |
rep(e[4], length(y) + 1)), col='white', border=NA) | |
polygon(c(min(x), x, max(x), rev(x)), | |
c(e[3], ifelse(y < 0, y, 0), | |
rep(e[3], length(y) + 1)), col='white', border=NA) | |
lines(x, y) | |
abline(h=0) | |
box() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Examples