Hello, I have a dataframe with 3 values and that I would like to plot with contour: ```> head(df)Y X Z 1 0.0008094667 50 1 2 0.0012360955 50 1 3 0.0016627243 50 1 4 0.0020893531 50 1 5 0.0025159819 50 1 6 0.0029426108 50 1> contour(df$X, df$Y, df$Z)Error in contour.default(df$X, df$Y, df$Z) : increasing 'x' and 'y' values expected ``` Y is increasing, whereas X is decreasing. How shall I set the function? Thank you
On 16/11/2021 3:45 a.m., Luigi Marongiu wrote:> Hello, > I have a dataframe with 3 values and that I would like to plot with contour: > ``` >> head(df) > Y X Z > 1 0.0008094667 50 1 > 2 0.0012360955 50 1 > 3 0.0016627243 50 1 > 4 0.0020893531 50 1 > 5 0.0025159819 50 1 > 6 0.0029426108 50 1 >> contour(df$X, df$Y, df$Z) > Error in contour.default(df$X, df$Y, df$Z) : > increasing 'x' and 'y' values expected > ``` > Y is increasing, whereas X is decreasing. How shall I set the function? > Thank you >Contour needs the Z data in a grid, with the X and Y data corresponding to rows and columns. The interp::interp() function in the interp package should be able to convert your data to this format; see its help page. An alternative is the akima::interp() function, which may have licensing issues. Duncan Murdoch
On Tue, 16 Nov 2021 09:45:34 +0100 Luigi Marongiu <marongiu.luigi at 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' ) contour( 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, Ivan