Is it possible to plot a curve with changing colours under a single plot?
Ältere Kommentare anzeigen
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?
Akzeptierte Antwort
Weitere Antworten (1)
Benjamin Kraus
am 29 Mai 2023
Bearbeitet: Benjamin Kraus
am 29 Mai 2023
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 Kommentar
DGM
am 29 Mai 2023
For some reason I can't upvote this. Let this comment be my upvote!
Kategorien
Mehr zu Line Plots finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!






