Is it possible to plot a curve with changing colours under a single plot?
古いコメントを表示
A would like to plot a curve with different colour line segments, and I need to do it under a single plot handle. Is it possible to do with the standard plot function, or I need something else?
採用された回答
その他の回答 (1 件)
Benjamin Kraus
2023 年 5 月 29 日
編集済み: Benjamin Kraus
2023 年 5 月 29 日
As others have noted, you cannot use the plot or line commands to create a multi-color line in MATLAB today, but this is possible in MATLAB, without using multiple line objects or even more scatter points.
The best way to plot a single multi-color line in MATLAB today is using the patch command. In fact, there is even an example in the doc that shows how to do it.
Patches are ordinarily used to draw filled regions, but if you insert a NaN into the vertices, then patch can be used to draw lines instead. And, multi-color lines in a Patch object is fully supported and documented, by setting the EdgeColor to interp and then setting either the CData or FaceVertexCData.
Here is an amended version of the example from the doc that includes wide lines and adjusting the LineJoin to get a different connection between individual segments:
figure
x = linspace(1,10,15);
y = sin(x);
y(end) = NaN;
c = y;
patch(x,y,c,'EdgeColor','interp','LineWidth',5,'LineJoin','round');
And, to emphasize how LineJoin works in this case, here is another example:
figure
nverts = 10;
x = rand(nverts,1);
y = rand(nverts,1);
c = turbo(nverts+1);
v = [x y; NaN NaN];
f = 1:nverts+1;
patch('Vertices',v, ...
'Faces',f, ...
'FaceVertexCData',c, ...
'EdgeColor','interp', ...
'LineWidth',10, ...
'LineJoin','round');
1 件のコメント
DGM
2023 年 5 月 29 日
For some reason I can't upvote this. Let this comment be my upvote!
カテゴリ
ヘルプ センター および File Exchange で Line Plots についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!






