[R] How to use contour plot?

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Tue Nov 16 11:28:41 CET 2021

On Tue, 16 Nov 2021 09:45:34 +0100
Luigi Marongiu <marongiu.luigi using gmail.com> wrote:

> contour(df$X, df$Y, df$Z)  

contour() works on matrices (sometimes called "wide format" data). Z
must be a numeric matrix, X must be a numeric vector with length(X) ==
nrow(Z), and Y must be a numeric vector with length(Y) == ncol(Z). This
is described in ?contour.

Since you have a three-column data.frame ("long format" data), you can
use lattice::contourplot instead (e.g. contourplot(Z ~ X + Y, data =
df)) or the appropriate combination of ggplot2 functions.

Alternatively, if your data is already on a grid, you can make a matrix
out of your three-column data.frame, but the procedure is a bit awkward:

ret <- reshape(
 df, direction = "wide", v.names = 'Z', idvar = 'X', timevar = 'Y'
 X <- ret[, 1],
 Y <- attr(ret, "reshapeWide")$times,
 Z <- as.matrix(ret[,-1])

(Can be also done with xtabs(); reshape2 and many other contributed
packages also offer some ways of doing that.)

Best regards,

More information about the R-help mailing list