# Change color of graph at a certain value (temperature vs. time)

6 views (last 30 days)
KNL on 24 Feb 2020
Answered: Star Strider on 24 Feb 2020
Hi,
I want to plot temperatures (type double) vs. time (type datetime). When the temperatures are below zero, I want the graph to be blue, and above zero I want it to be red. How can I do this? I know this has been discussed before, but I am struggeling due to the datetime on the x-axis. I still want the x-ticks to show up as dates. The file is attached
Thank you:)

Just plot it as you would normally, but with two separate operations. Plot only the above zero part and specify it to be red and plot only the below zero part separately and specify it to be red.
e.g.
plot( hAxes, x( y > 0 ), y( y > 0 ), 'r' )
hold( hAxes, 'on' );
plot( hAxes, x( y <= 0 ), y( y <= 0 ), 'b' )
or put 0 in the red section, or plot it its own colour if you prefer. Where hAxes is your axes handle. You can leave that out if you wish to just take your chances as to where things plot, but I almost always include it in my answers.
KNL on 24 Feb 2020
Thank you. This does however plot two separate graphs, as shown below. I would like it to be only onle graph, but changing between red and blue when crossing 0. the cyclist on 24 Feb 2020
One option would be to draw the data as points, perhaps with a thin black line to guide the eye to time-consecutive points.
rng default
N = 50;
x = 1:N;
y = rand(1,N);
hotThreshold = 0.5;
isHot = y > hotThreshold;
figure
hold on
hH = plot(x(isHot),y(isHot),'r.');
hC = plot(x(~isHot),y(~isHot),'b.');
set([hH,hC],'MarkerSize',36)
plot(x,y,'k')
yline(hotThreshold,'--') #### 1 Comment

the cyclist on 24 Feb 2020
If that doesn't look great to you, I think your only other option is to make piecewise colored lines, by looping over your data to see which segments are above/below your threshold.

Star Strider on 24 Feb 2020
This eliminates the connections between the ‘gaps’ in the red and blue areas:
temph = temp;
temph(temp <= 0) = NaN;
tempc = temp;
tempc(temp > 0) = NaN;
figure
plot(time, temph, '-r')
hold on
plot(time, tempc, '-b')
hold off
grid
producing this plot: The only way to fill the gaps around C is to interpolate to a time vector with more points within the same limits. This is your data, so I leave that to you to determine if that is appropriate. Note that interpolating adds data where no data existed previously, so for a plot that may be appropriate, however for data analysis it would not be at all appropriate.