Shading to indicate a condition on a time series plot

17 次查看(过去 30 天)
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

采纳的回答

Star Strider
Star Strider 2014-7-31
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.

更多回答(1 个)

Chad Greene
Chad Greene 2014-8-4
Alternatively, you could use vfill.

类别

Help CenterFile Exchange 中查找有关 Annotations 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by