Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradient legend in base

Tags:

plot

r

Earlier I asked about creating a gradient of n values in base graphics (LINK). Now I'd like to create a gradient legend that goes with it. My ideal would be something like ggplot2's gradient legends:

enter image description here

Here's some code similar to what I'm working with:

colfunc <- colorRampPalette(c("red", "blue"))
plot(1:20, 1:20, pch = 19, cex=2, col = colfunc(20))

enter image description here

like image 807
Tyler Rinker Avatar asked Nov 13 '12 03:11

Tyler Rinker


3 Answers

Here is an example of how to build a legend from first principles using rasterImage from grDevices and layout to split the screen

layout(matrix(1:2,ncol=2), width = c(2,1),height = c(1,1))
plot(1:20, 1:20, pch = 19, cex=2, col = colfunc(20))

legend_image <- as.raster(matrix(colfunc(20), ncol=1))
plot(c(0,2),c(0,1),type = 'n', axes = F,xlab = '', ylab = '', main = 'legend title')
text(x=1.5, y = seq(0,1,l=5), labels = seq(0,1,l=5))
rasterImage(legend_image, 0, 0, 1,1)

enter image description here

like image 97
mnel Avatar answered Nov 06 '22 01:11

mnel


Late to the party, but here is a base version presenting a legend using discrete cutoffs. Thought it might be useful for future searchers.

layout(matrix(1:2,nrow=1),widths=c(0.8,0.2))
colfunc <- colorRampPalette(c("white","black"))

par(mar=c(5.1,4.1,4.1,2.1))
plot(1:10,ann=FALSE,type="n")
grid()
points(1:10,col=colfunc(10),pch=19,cex=1.5)

xl <- 1
yb <- 1
xr <- 1.5
yt <- 2

par(mar=c(5.1,0.5,4.1,0.5))
plot(NA,type="n",ann=FALSE,xlim=c(1,2),ylim=c(1,2),xaxt="n",yaxt="n",bty="n")
rect(
     xl,
     head(seq(yb,yt,(yt-yb)/10),-1),
     xr,
     tail(seq(yb,yt,(yt-yb)/10),-1),
     col=colfunc(10)
    )

mtext(1:10,side=2,at=tail(seq(yb,yt,(yt-yb)/10),-1)-0.05,las=2,cex=0.7)

And an example image:

enter image description here

like image 23
thelatemail Avatar answered Nov 06 '22 02:11

thelatemail


The following creates a gradient color bar with three pinpoints without any plot beforehand and no alien package is needed. Hope it is useful:

plot.new()
lgd_ = rep(NA, 11)
lgd_[c(1,6,11)] = c(1,6,11)
legend(x = 0.5, y = 0.5,
       legend = lgd_,
       fill = colorRampPalette(colors = c('black','red3','grey96'))(11),
       border = NA,
       y.intersp = 0.5,
       cex = 2, text.font = 2)
like image 5
MCH Avatar answered Nov 06 '22 02:11

MCH