Search code examples
matlabplot3dmatlab-figure

How to get vertical lines in a 3D scatter plot in matlab?


I have three matrices x, y, z which are plotted via scatter3 in matlab. However I also need vertical lines dropping from every point in the graph for better visualization.

Using matlab 2017a, implemented 3D scatter plot in matlab.

enter code here
clc;
figure
x = [0,0,0,0,0,10,10,10,10,10];
y = [0,10,20,30,40,-10,0,10,20,30];
z = [46,52,51,59,53,85,56,87,86,88];
scatter3(x, y, z, 30, 'filled')

Solution

  • As @SardarUsama pointed out, plot3 should do the trick. Code could be more compact but kept it as is for clarity.

    Vertical lines on 3d scatter plot

    % MATLAB R2017a   
    x = [0,0,0,0,0,10,10,10,10,10];
    y = [0,10,20,30,40,-10,0,10,20,30];
    z = [46,52,51,59,53,85,56,87,86,88];
    
    figure
    scatter3(x, y, z, 30, 'filled')  % scatter plot (3D)
    zRng = zlim;
    hold on
    for k = 1:length(x)
        xL = [x(k) x(k)];
        yL = [y(k) y(k)];
        zL = [zRng(1) z(k)];
        plot3(xL,yL,zL,'r-')         % plot vertical line (3D)
    end