Is it possible to add gradient color to 2-D line in Matlab, especially when you have small number of data points (less than 10?), so the result would be similar to one in image below?
Asked
Active
Viewed 1.6k times
2 Answers
9
This is not difficult if you have MATLAB R2014b or newer.
n = 100;
x = linspace(-10,10,n); y = x.^2;
p = plot(x,y,'r', 'LineWidth',5);
% modified jet-colormap
cd = [uint8(jet(n)*255) uint8(ones(n,1))].';
drawnow
set(p.Edge, 'ColorBinding','interpolated', 'ColorData',cd)
Which results in:
Excerpted from Undocumented Features - Color-coded 2D line plots with color data in third dimension. The original author was thewaywewalk. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 2383 and example ID: 7849.

Jon 'links in bio' Ericson
- 20,880
- 12
- 98
- 148

Dev-iL
- 23,742
- 7
- 57
- 99
-
Thank you for the solution! – Claude Monet Feb 11 '17 at 14:05
5
Here's one possible approach: explicitly plot each segment of the line with a different color taken from the desired colormap.
x = 1:10; % x data. Assumed to be increasing
y = x.^2; % y data
N = 100; % number of colors. Assumed to be greater than size of x
cmap = parula(N); % colormap, with N colors
linewidth = 1.5; % desired linewidth
xi = x(1)+linspace(0,1,N+1)*x(end); % interpolated x values
yi = interp1(x,y,xi); % interpolated y values
hold on
for n = 1:N
plot(xi([n n+1]), yi([n n+1]), 'color', cmap(n,:), 'linewidth', linewidth);
end

Luis Mendo
- 110,752
- 13
- 76
- 147