A 3D scatter plot of a Cartesian data set is drawn. The data points are sorted by color and plot3 is called once for each group of points that map to the same color. This reduces execution time significantly for large data sets. By default the points are colored according to their distance from the XY plane. This can changed with the 'ColorData' property. Additionally the upper and lower limits of the color range can be specified. This is useful for creating a series of plots with the same coloring.
The example plot is produced by the following code.
figure('color','white');
[x,y,z] = peaks(101);
c = gradient(z);
k = hypot(x,y)<3;
plot3k({x(k) y(k) z(k)}, ...
'Plottype','stem','FontSize',12, ...
'ColorData',c(k),'ColorRange',[0.5 0.5],'Marker',{'o',2}, ...
'Labels',{'Peaks','Radius','','Intensity','Lux'});
Plot3k is based on plot3c by Uli Theune.
Ken Garrard (2020). Color coded 3D scatterplot (https://www.mathworks.com/matlabcentral/fileexchange/9519colorcoded3dscatterplot), MATLAB Central File Exchange. Retrieved .
1.8.0.0  Added a stem3 style with colored lines from the xy plane


1.7.0.0  This update excludes points with NaN color values from the plot. 

1.6.0.0  Updated treatment of NextPlot property as suggested by Val. 

1.4.0.0  Bug fix for 'ColorData', 'ColorRange' properties. 

1.3.0.0  Optional arguments are property,value pairs. Input data can be a cell array, vector or matrix. 

1.1.0.0  The color range and markersize arguments have been added. The figure handle is not returned unless an output argument is given. 
Inspired by: plot3c
Create scripts with code, output, and formatted text in a single executable document.
Thank you for this code. How to remove the marker at the intersection of X and Y axis ?
How would I used this to plot 4 variables in a timetable? I have diesel consumption, engine load, engine power, and I want to color by rpms.
Thank you! this is exactly what I was hoping for!
Strange problem I encountered but not sure if I'm alone or if anyone cares but would have saved me time to know... I have a code where I sorted my x,y,z values according to my z values, e.g.:
[z, ii] = sort(z);
x = x(ii);
y = y(ii);
z = z(ii);
My other plots have no problem with this. But for some strange reason, plot3k only uses the sorted z values but not the sorted x,y so the plotted values were incorrect. After scratching my head for a while, all I had to do was use the plot3k before I sorted (since I no longer need the sort function to highlight my lowest errors which are 'z')
I am using R2017a on Linux. When using this script to plot, the colour bar is displayed as one solid colour instead of varying colours. However, this does not happen on a Mac. Does anyone have a similar issue?
Are there any known problems with this function under MATLAB R2016b (academic student use on Ubuntu 16.04 64bit), and if so, is there a newer version/other option for xyzplotting?
In my case it refuses to plot the data, but scales, grid and number/position of subplots are OK.
Any advice is appreciated!
Thanks
Much better speed than scatter, thanks.
Sudharsana,
Before calling plot3k open a new figure using the colormap of your choice.
For example,
figure('colormap',jet);
plot3k(peaks(41));
hi,
I am new in using this. I used this to plot a 3d data in Matlab 2015.
By defualt it is taking the color map as parula. is there a way to change it.
do I have to add the syntax
'color map','jet' (or anything elsewhere)
let me know thanks.
By the way it is in an excellent submission. Ken u rock.
Great job Ken!
Great job Ken!
Would there be a quick way to plot each individual point by RGB color value? I know scatter3 has this capability but it is extremely slow.
I found the colorbar unnecessary for most of my 3D arrays, but quite useful for plotting 4D arrays. I added an element to the p structure called "ColorBar" which is checked before generating the colorbar. Then doing plot3k(...,'ColorBar',true,...) can be used to create the plot with the colorbar.
Hi everyone,
I have a 4D dataset similar and want to use this commands. I am totally new to Matlab. I imported the data from excel and biuld a Matrix:
Points=[g psi microstrain f]:
Each letter has a column of datapoints. When I use the commands above I always get the error:
Undefined function for plot3k for input arguments of type cell.
I tried a lot and dont have a solution.
Can anyone help me?
Hi Ken, I guess i'm just repeating previous comments but this is fantastic compared to scatter3. Any idea why it is so much faster? Is it because it plots multiple smaller series? With scatter3 plotting is a slow but working on the graph (rotating, editing properties, saving to jpeg) really brings my computer to its knees. Thanks again.
Thanks a million Ken! :) I should have thought of that.
PS. I tried downloading the plot3k file again and its still the same version. I have added the necessary line on my end. Thanks!
Carlyle, Points with a NaN color value can be excluded by setting the Z value for those points to NaN. For (x,y,z) data with color vector c, 'z(isnan(c))=NaN'. An updated plot3k has been submitted.
Hi Ken, I was just using this code and noticed that it does not ignore NaN values for the colourcoded points. Is there a way to make the code NOT plot the (x,y,z) point if the associated colourvalue for that point is NaN?
Jackson, Use either 'hold on' or 'axes(h)' before calling plot3k to plot into the current axes or the axes with handle 'h'.
Works great. One question, is it possible to place the plot on an existing set of axes?
MUCH quicker than scatter3(). What a lifesaver!
great! Thanks for sharing, Ken!
This is brilliant. Thanks, Ken
works great!
Thanks for the suggestion Val. I'll update the submission.
This is a fantastic utility  something that should be incorporated into MATLAB proper, as scatter3 is awful.
I do recommend one change however. Currently, plot3k calls "hold on" prior to plotting anything which means you'll always add to whatever figure window is active. Since this is not the default behavior of MATLAB I find it a hassle.
The fix is to move 'hold on' on line 164 so the plotting loop looks like this:
snip
% plot data points in groups by color map index
s = 1; % index of 1st point in a color group
for k = 1:length(dLix) % loop over each nonempty color group
plot3(L(s:dLix(k),1), ... % call plot3 once for each color group
L(s:dLix(k),2), ...
L(s:dLix(k),3), ...
mark_ch, ...
'MarkerSize',mark_sz, ...
'MarkerEdgeColor',cmap(L(s,4),:), ... % same marker color from cmap
'MarkerFaceColor',cmap(L(s,4),:) ); % for all points in group
s = dLix(k)+1; % next group starts at next point
if k==1
hold on; % add points to one set of axes
end
end
hold off;
snip
Great code. One small improvement:
Change length(L) to size(L,1) on 96 and 141 lines. Otherwise, it's not working with one data point
Is it possible to use this code to scan images with laser stripe in it and plot out the 3D point cloud of the laser traced portion? with depth?
Kindly help me out
After trying and failing to plot my data (3e6 points) using scatter3, this little guy did it for my licketysplit. Is a 4D set, so plotting first 3 dimensions as spatial, and fourth as color. Just had to make sure my nargs matched up via cells, so did {data(:,1) data(:,2) data(:,3)} as first arg to plot3k, and data(:,4) as second for color.
A+ rating from this matlab user.
Simple, fast and clean. VERY good job! Thank you!
minor grid does not show up on Zaxis when Zscale is set to log
(i.e. set(gca,'zscale','log');
any idea why this is occuring?
I would suggest to change "length(L)" to "size(L,1)" since when points are too less (i.e. less than 3), error will happen. Besides that, it is great! Thanks:)
Very good  its way quicker than scatter3. Uses much less memory :)
Very useful indeed !
Something I was missing in it:
 A label for the color bar, that could be passed in the 'strs' together with the title and the rest of the labels.
If somebody wants that, just tell me, I added that
Thanks again !
very good job! thank you!
excellent file.
For those interested in additional functionality in terms of viewing contours and slices through 3d data, check out:
http://www.paraview.org
very nice indeed! any chance of further speed optimization?
one that you should never miss!
Holy Jehosaphat!! worked outta the box! The funktion did exactly what i just spent the last hour trying to do! what a fantastic function for scientifik data! you're my hero!!!!
thanks x 10!
Exactly what I was looking for. Thank you.
Nice!
I would add a:
if nargout>0
g = gcf;
end
That way you get a cleaner function if you don't need the output.
Thanks a lot, very useful
It "rocks"; it allows a "surf"like plot without the hassles and inaccuracies of preppoing the dating over a regular grid!
Firstrate work.
Great, does just what I wanted.
Very useful function
thank you, I've been looking for such a function for ages! ;)
your are a genious
Just what I was looking for  works great.
Great function. Work well and is fast.