Matlab 中的二维线渐变颜色

2-D line gradient color in Matlab

是否可以在 Matlab 中为二维线添加渐变颜色,尤其是当您的数据点数量较少(少于 10 个?)时,结果会类似于下图吗?

如果您有 MATLAB R2014b 或更新版本,这并不困难。

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)

这导致:

摘自 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。参考题目ID:2383 范例ID:7849.

这是一种可能的方法:使用取自所需颜色图的不同颜色显式绘制线条的每一段。

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