[R] question on contour function

David Winsemius dwinsemius at comcast.net
Thu Aug 12 02:54:00 CEST 2010


On Aug 11, 2010, at 11:16 AM, ba ba wrote:

> Dear All,
>
> I tried to plot contour lines using R function contour, but got the  
> results
> which are not expected.
>
> require(RTOMO)
> x <- seq(-1,1,0.1)
> y <- seq(-1,1,0.1)
> xy <- meshgrid(x,y)
>
> z <- xy$x^2+ 3*xy$y^2
> contour(x,y,z,col="blue",xlab="x",ylab="y")
>
> The above code gave me the contour graph for z=3*x^2+y^2 rather than
> z=x^2+3*y^2. Is anyone know the reason?

Because contour was expecting a matrix of z values for z and you gave  
it a list created by a function you did not understand?

 > meshgrid
function (a, b)
{
     return(list(x = outer(b * 0, a, FUN = "+"), y = outer(b,
         a * 0, FUN = "+")))
}

Instead:
Use the base function outer():

 > x <- seq(-1,1,0.1)
 > y <- seq(-1,1,0.1)
 > xy <- outer(x,y, FUN=function(x,y) x^2+ 3*y^2)
 >
 >
 > contour(x,y,xy,col="blue",xlab="x",ylab="y")

-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list