Shading to indicate a condition on a time series plot
14 views (last 30 days)
Show older comments
I have a long time series, let's say of water level in a stream, shown on a line plot. I would like to shade in periods when a certain condition is true, let's say when it was raining. This shading would appear as light gray vertical blocks for every rainy time period, for example using the fill command. What do I need to add to the code below?
% Make fake time series of water level
t = 0:0.1:10; % Time
w = sin(2*pi*t); % Water level
% Make fake logical condition indicating when it's raining
iRain = false(size(t));
iRain([5:10 20 40:42 50 60:75 90:95]) = true; % Periods when it's raining, some very short
% Make line plot of water level
plot(t, w);
hold on;
f = fill(??); % Add vertical bars/blocks to indicate periods when iRain is true
0 Comments
Accepted Answer
Star Strider
on 31 Jul 2014
I had to make some changes in your code, and since I have more expreience with patch than fill in these situations, I used it instead.
It could probably be more efficient, but it has the virtue of working:
% Make fake time series of water level
t = 0:0.1:100; % Time
w = sin(2*pi*t) + 1; % Water level
% Make fake logical condition indicating when it's raining
iRain = false(size(t));
iRain([5:10 20 40:42 50 60:75 90:95]) = true; % Periods when it's raining, some very short
xRain = {5:10; 20; 40:42; 50; 60:75; 90:95};
% Make line plot of water level
figure(1)
plot(t, w);
hold on
for k1 = 1:size(xRain,1)
q = xRain{k1};
if length(q) == 1
q = [q q+0.1];
end
qx = [min(q) max(q) max(q) min(q)];
yl = ylim;
qy = [[1 1]*yl(1) [1 1]*yl(2)];
patch(qx, qy, [1 1 1]*0.8)
end
plot(t, w);
hold off
grid
Experiment with it to get the result you want.
The ‘[1 1 1]*0.8’ sets the colour to light gray.
It calls plot(t,w) twice, once to set the axes limits, and the second to plot the data over the gray stripes.
The cell array xRain creates a cell array out of your rain period vector. It makes it easier to define the periods, and from them create the gray stripes. For those entries defined by one number and not a range, I created a narrow range for them with the ‘if’ block. You can lengthen that range (currently 0.1) if you want.
The ‘yl’ variable is used to create stripes that go the height of the plot.
More Answers (1)
See Also
Categories
Find more on Annotations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!