Search code examples
plotoctavescatter3d

x and y axis interchanged in scatter3 plot in GNU Octave


Suppose I want to plot f(x,y,z) = x^2 using the scatter3 function of GNU Octave. My code is

x = [1,2,3,4];
y = [1,2,3,4,5];
z = [1,2,3,4,5,6];

for xi = 1:4
    for yi = 1:5
        for zi = 1:6
            a(xi,yi,zi) = x(xi) * x(xi);
        endfor
    endfor
endfor

[xx yy zz] = meshgrid(x,y,z);
scatter3(xx(:), yy(:), zz(:), [], a(:),'fill');
xlabel('x')
ylabel('y')
zlabel('z')
colormap(rainbow)
colorbar()

enter image description here I am getting the above plot, which shows that the function changes with y (it is actually y^2), and is a constant w.r.t. x. Am I doing something wrong? Since a(xi,yi,zi) = x(xi) * x(xi), should not I get a = x^2 instead, due to the index xi?

I have labelled the three axes.

I am using Octave 4.2.2 in Ubuntu 18.04.


Solution

  • Swap x and y axes in your function matrix.

    a(yi,xi,zi) = x(xi) * x(xi);
    

    This is necessary due to the way meshgrids work in scatter plots. In your case, the x and y axes are flipped to Octave. You need to flip them before you plot to get the expected output.

    From the documentation:

    The surface mesh is plotted using shaded rectangles. The vertices of the rectangles [x, y] are typically the output of meshgrid. over a 2-D rectangular region in the x-y plane. z determines the height above the plane of each vertex. If only a single z matrix is given, then it is plotted over the meshgrid x = 1:columns (z), y = 1:rows (z). Thus, columns of z correspond to different x values and rows of z correspond to different y values.

    (Text in italic deliberately highlighted)