Plotting Gradients in R

fadeThere might be an easier way to do this, but here’s one way to plot gradients in R. It draws on colorRampPalette() and a for() loop, and isn’t very fast on underpowered machines — but it works. Using colorRampPalette() we can create the necessary gradients. Here’s the code I cobbled together:

fade <- function(M=1, S=1, Y=1, H=0.05, K=50, dk = "black") {
# M = midpoint; S = spread; Y = position; H = height; K = steps in gradient; dk = dark colour
colfunc <- colorRampPalette(c(dk, "white")) # creates a function to produce the gradients
D <- S/K # delta; how wide does one rectangle have to be?
collist <- colfunc(K) # create K colours
for(i in 0:(K-1)) { # draw rectangles; K-1 because I start with 0 (this makes it easier in the line just below)
rect(M+(D*i), Y-H, M+D+(D*i), Y+H, col=collist[i+1], border=NA) # drawing a narrow rectangle, no borders drawn; to right
rect(M-(D*i), Y-H, M-D-(D*i), Y+H, col=collist[i+1], border=NA) # to left
}
}

Before applying the above code, we need an empty plot:

plot(1, ylim=c(0.5,8), xlim=c(1,8), type="n", axes=F, xlab="", ylab="")

Important are the ylim and xlim arguments, and the type="n" to plot nothing. I usually prefer drawing my own axes — axis(1), axis(2) as this allows easy customization…

Why not highlight the midpoint? We can this as follows:

text(M, Y, "|", col="white", font=4) # font = 4 for bold face

In many cases, the package denstrip may offer an easier solution, albeit one where we have less control.

P.S. The code produces just one of the lines in the plot included at the top.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s