Use textscan to read your data:
fid = fopen('/My Documents/filename.dat');
data = textscan(fid, '%f %f %f');
fclose(fid);
X=data{1};
Y=data{2};
Z=data{3};
Plot method #1
Then if you plot with
plot(X,Y)
you'll get an ordinary plot consisting of lines. However these all have the same color. Varying them is not possible unless you split them up in separate lines.
Luckily, there is also the scatter function which allows you to do this:
scatter(X,Y,[],Z)
This plots the points, with color based on Z.
Plot method #2
If you want the points to be connected with lines also having varying color, you'll have to plot them as separate lines, and providing color to each line separately:
plot([X(1:end-1)' ; X(2:end)'], [Y(1:end-1)' ; Y(2:end)']);
The lines now have default coloring, it becomes a bit a hussle to get the right colors in however, next up is an example. Unfortunately I don't now of any way to input the colors also in such a one-liner, so we'll have to loop.
Ncolors=10;
zmin=min(Z);zmax=max(Z);
dz=max((zmax-zmin)/Ncolors,eps);
clr_map=jet(Ncolors);
clr_ids=min(floor((Z(1:end-1)-zmin)/dz)+1,Ncolors);
figure;hold on;
for ii=1:numel(X)-1
plot([X(ii) X(ii+1)], [Y(ii) Y(ii+1)],'color',clr_map(clr_ids(ii),:))
end
All lines now have colors based on one of their end points.
To add a colorbar, use colorbar
, weird huh? But of course, the labels of that bar are referring to the colororder. Luckily, we can change them:
colormap(clr_map);
h_cb=colorbar;
set(h_cb,'yticklabel',arrayfun(@num2str,linspace(zmin,zmax,numel(get(h_cb,'ytick'))),'uni',false));
Change Ncolors
to use more/less resolution in coloring the lines.
Probably overkill: you can also change the number of labels on the colorbar, the following changes it to 10:
colormap(clr_map);
h_cb=colorbar;
set(h_cb,'ytick',linspace(1,Ncolors,10));
set(h_cb,'yticklabel',arrayfun(@num2str,linspace(zmin,zmax,10),'uni',false));
or now with the labels having only 2 decimals:
set(h_cb,'yticklabel',arrayfun(@(yi) sprintf('%.2g',yi),linspace(zmin,zmax,10),'uni',false));
Plot method #3
Another last method is to use patches (which are slower), which is explained for the 3d case here, so you can get started there if you want.