I'm producing a heat map with the function image():
testmatrix <- matrix(rnorm(100), nrow=10)
image(1:10,1:10,testmatrix)
I need each cell to display the value inside them, but so far haven't found a way to do it. This functionality doesn't seem to be integrated in the function itself. Is there a way to do this?
(I know heatmap() could do this more straightforwardly, but I am forced to use image() to later integrate the code into another function.)
CodePudding user response:
Using text
:
testmatrix <- matrix(rnorm(100), nrow=10)
image(1:10, 1:10, testmatrix)
# Create a grid with x, y, and values (z)
grid <- expand.grid(x = seq(nrow(testmatrix)), y = seq(ncol(testmatrix)))
out <- transform(grid, z = testmatrix[as.matrix(grid)])
txt <- out[order(out$x), ]
text(txt$x, txt$y, round(txt$z, 2))
CodePudding user response:
CodePudding user response:
You can use row(testmatrix)
and col(testmatrix)
as x
and y
arguments when calling text
testmatrix <- matrix(rnorm(100), nrow=10)
image(1:10,1:10,testmatrix)
text(x = row(testmatrix),
y = col(testmatrix),
label = sprintf("%.2f", testmatrix))