SumRchn
SumRchn

Reputation: 3

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

Upvotes: 0

Views: 3519

Answers (2)

Hoki
Hoki

Reputation: 11812

You could also use the built in function stem, which is doing exactly that.

The minor trick is that you cannot pass the z coordinates in the shorthand form stem(x,y,z), but the graphic object still accept z data, you just have to send them as additional parameter.

The nice part of it is you do not need a loop ;-)

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

hp = stem(x,y,'filled','ZData',z) ;

Or as Gnovice nicely pointed out, even easier to use the stem3 function which accept z data directly:

hp = stem3(x,y,z,'filled') ;

Both example above will produce:

enter image description here

Upvotes: 2

SecretAgentMan
SecretAgentMan

Reputation: 2854

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

Upvotes: 1

Related Questions