Home > OS >  Add border to rasterImage
Add border to rasterImage

Time:01-03

Here is a gradient color legend I created using rasterImage:

colfunc <- colorRampPalette(c("red", "blue"))
legend_image <- as.raster(matrix(colfunc(20), ncol=1))
plot.new()
rasterImage(legend_image, 0.9, 0, 1, 1)     
lbsq <- seq.int(0, 1, l=5)                                  
axis(4, at=lbsq, pos=1, labels=F, col=0, col.ticks=1, tck=-.05) 
mtext(lbsq, 4, -.2, at=lbsq, las=2, cex=.6)

I wish to add a thin black border surrounding the color legend. I tried to add lty = 1 in rasterImage, which did not work. My question is how to add a black border to the resultant image and adjust its color and width.

CodePudding user response:

You could slightly increase the margins and use box().

colfunc <- colorRampPalette(c("red", "blue"))
legend_image <- as.raster(matrix(colfunc(20), ncol=1))
plot.new()
rasterImage(legend_image, -.1, -.1, 1.1, 1.1)
box(lwd=3)

You could also play with the pars.

png('test.png', 600, 400)

plot.new()
par(new=TRUE, mar=c(5.8, 40, 4, 4))
rasterImage(legend_image, .9, 0, 1.1, 1.1)
box(lwd=1)
par(mar=c(5.4, 4, 3.9, 4.8) .1, new=TRUE)
plot(1:10)

dev.off()

enter image description here

Note, that this is rather unstable while working with the plotting preview window, definitely enter image description here

  • Related