How can i represent elevation (z) in different colors using plot function?

I' am plotting distance (h) which is the x-axis against elevation (z)which is y-axis using the plot function in MATLAB.
The output figure i get is a single red line. But i want to represent the single line in different colors according to elevation with a color bar
cheers

 Accepted Answer

That's not a straightforward thing to do;
h = axes;
x = (1:10)';
y = rand(1,10);
minY = min(y);
intY = max(y) - minY;
lH = plot(x,y); hold on
colors = colormap('jet');
numDiv = 100;
for ii = 2 : numel(x);
sub_x = linspace(x(ii-1),x(ii),numDiv);
sub_y = linspace(y(ii-1),y(ii),numDiv);
for jj = 2 : numel(sub_y)
temp_y = (sub_y(jj-1) + sub_y(jj) ) / 2;
idx = ceil( (temp_y - minY) ./ intY * size(colors,1));
plot([sub_x(jj-1) sub_x(jj)], [sub_y(jj-1) sub_y(jj)], ...
'Linestyle','-','Color',colors(idx,:));
end
end
delete(lH)
set(h,'CLim',[min(y),max(y)]);
colorbar;

3 Comments

There's actually a simpler/faster (but less obvious) way.
While the line object that plot creates won't interpolate color data, the patch object will, and you can turn of the face of the patch to get the effect you want:
h = axes;
x = 1:10;
y = rand(1,10);
patch([x, nan], [y, nan], [y, nan], ...
'FaceColor','none', 'EdgeColor','interp')
colorbar
What's going on here is that we called the "XYC" form of patch with X, Y, and Y. That's telling it to use Y as the color data. In addition, we added a nan to the end of the data. That tells patch that it shouldn't connect the end back to the beginning, like it usually does. Finally, we set the FaceColor to 'none' (because we don't want the patch filled) and we set the EdgeColor to 'interp' (because we want it to interpolate the data and then use that interpolated value to do a color lookup).
You'll find that this approach is usually much faster than creating a bunch of line objects, and it makes it much easier to modify your plot after the fact.
Does that make sense?

Sign in to comment.

More Answers (1)

sorry may question i think is simpler but i don't know how to do it, i have let's say 10 orbits in the same figure and each orbit have a different energy level, i want that each line with a different colour based on the energy and the same as colourmap jet..thanks for the answer

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!