0

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?

Ash
  • 85
  • 5

1 Answers1

1

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

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • Just a quick update. When I plot with **colkey** argument as you suggested I get this [plot](https://i.stack.imgur.com/BRHeL.png) . The legend is _wider_ than the actual plot in RStudio. How did you align the width of the plot to be the same as the width of the legend. – Ash Jul 30 '23 at 22:26
  • @Ash that's just down to the plotting device settings. Try changing the aspect ratio or adjusting `par(mar = ....)` – Allan Cameron Jul 30 '23 at 22:36