rmatrixplotlegendcovariance-matrix

Horizontal legend for a covariance matrix plot


I am trying to construct a 2D perspective plot of a covariance matrix in R. A reprex code is below

nrows <- 10
ncols <- 10
p <- nrows * ncols

Qvariance <- 1
Qrho <- 0.8

alpha <- matrix(rep(1:p, p), nrow = p, ncol = p)
JJ <- (alpha - 1) %% nrows + 1
II <- floor((alpha - JJ) / ncols) + 1
LL <- t(JJ)
KK <- t(II)
d <- sqrt((LL - JJ)^2 + (KK - II)^2)
Q <- Qvariance * (Qrho^d)

print(dim(Q))
Q[1:5, 1:5]

x <- 1:ncol(Q)
y <- 1:nrow(Q)

# Create a grid of x and y values
X <- matrix(x, nrow = nrow(Q), ncol = ncol(Q), byrow = TRUE)
Y <- matrix(y, nrow = nrow(Q), ncol = ncol(Q), byrow = FALSE)

library(plot3D)
persp3D(x = X, y = Y, z = Q, theta = 90, expand = 0.5, xlab = "Columns", ylab = "Rows", scale = FALSE)

The plot is here

enter image description here

I would like the legend to be placed in the bottom (horizontal). How do I do that with the persp3D() plot function?


Solution

  • You can use the colkey parameter to control various aspects of the legend. Using colkey = list(side = 1) will move the legend to the bottom.

    persp3D(x = X, y = Y, z = Q, theta = 90, expand = 0.5, 
            xlab = "Columns", ylab = "Rows", scale = FALSE,
            colkey = list(side = 1))
    

    enter image description here