Change line colour depending on y axis value
Afficher commentaires plus anciens
I have a graph with a blue line plotted that passes through a region around y=±2 (grey in the top image).
I want that line to change colour to also be grey only when it passes through this region (mockup in bottom image).
i.e. Above y=2 line is blue, between y=2 & y=-2 line is grey, below y=-2 line is blue. The format of the variable used to plot the line is also shown below.



Réponse acceptée
Plus de réponses (1)
Method one: FEX
Some of these might do what you want:
https://www.mathworks.com/matlabcentral/fileexchange/39972-colormapline-color-changing-2d-or-3d-line?
etc.
Method two: multiple axes
Here is a straightforward method that does not require data interpolation or any data manipulation. It works by simply overlaying a second axes on top of the first, and plotting exactly the same data. Note how the colored lines are "cut off" at the boundaries, even though there are no data points there!
X = (0:0.1:1)*2*pi;
Y = sin(X);
ub = +0.4; % upper bound
lb = -0.3; % lower bound
fgh = figure();
ax1 = axes('parent',fgh); % background
ax2 = axes('parent',fgh); % foreground
plot(ax1,X,Y,'-*','Color',[0,0,1],'LineWidth',2);
plot(ax2,X,Y,'-*','Color',[1,0,0],'LineWidth',2);
ylm = get(ax1,'YLim');
pos = get(ax1,'Position');
pos(2) = pos(4)*((lb-ylm(1))/diff(ylm))+pos(2);
pos(4) = pos(4)*(ub-lb)/diff(ylm);
set(ax2, 'Position',pos, 'Visible','off', 'YLim',[lb,ub])
hold(ax1,'on')
plot(ax1,X([1,end]),[ub,ub],'-') % horizontal line
plot(ax1,X([1,end]),[lb,lb],'-') % horizontal line
Giving:

Using three or four axes would allow complete control over how the lines appear, e.g. if the (dotted) lines "show through" from the backround axes.
Catégories
En savoir plus sur Line Plots dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

