Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a color legend to an image

Tags:

r

image

legend

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?

like image 527
user2113499 Avatar asked Mar 03 '13 17:03

user2113499


People also ask

What is image 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.


2 Answers

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.

like image 124
HelloWorld Avatar answered Oct 29 '22 14:10

HelloWorld


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)
like image 42
IRTFM Avatar answered Oct 29 '22 13:10

IRTFM