I have a matrix that I made an image of using image(matrix)
. Is there away to add a legend of the colors to my image like I do when adding a legend to plot?
Description. This function combines the R image function with some automatic placement of a legend. This is done by splitting the plotting region into two parts. Putting the image in one and the legend in the other. After the legend is added the plot region is reset to the image plot.
Or the legend could be provided like this:
legend(grconvertX(0.5, "device"), grconvertY(1, "device"),
c("0",".5","1"), fill = colMap[c(1, 10, 20)], xpd = NA)
where grconvertX() and grconvertY() and xpd makes sure the legend is outside the plotting region. A plausible example would be:
nsamples <- 20
mat <- rnorm(nsamples, .5, .15)
dim(mat) <- c(4, 5)
colMap <- colorRampPalette(c("red","white","blue" ))(nsamples)
image(1:4, 1:5, mat, col = colMap, ylab="", xlab="")
legend(grconvertX(0.5, "device"), grconvertY(1, "device"),
c("0",".5","1"), fill = colMap[c(1, 10, 20)], xpd = NA)
p.s.: I know it is an old request and it is solved. However I was looking for a similar answer and I could not find it. Since I bother solving this issue I thought maybe someone else could also benefit from it.
image
in R is a fairly basic plotting function. You might want to look at filled.contour
if you want a function that will automatically allocate space for a legend. Or try this:
library(lattice)
levelplot(matrix)
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