Duncan and David, thank you so much.

You are right. We can use
    z1 <- outer(x, y, function(x,y) x^2+3*y^2)
rather than
   xy <- meshgrid(x,y)
   z2 <- xy$x^2+ 3*xy$y^2
to get right answer.  I run these codes on my computer and found that z2 is
the transpose of z1.

So I guess in order to obtain the expected result, there are at least two
ways.

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

or
   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
   z <- t(z)
   contour(x,y,z,col="blue",xlab="x",ylab="y")

Of course, the first method is better since it only uses the base function.

David Lee

On 12 August 2010 01:54, David Winsemius <dwinsemius@comcast.net> wrote:

>
> 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
>
>

	[[alternative HTML version deleted]]

