Shading to indicate a condition on a time series plot

조회 수: 14 (최근 30일)
K E
K E 2014년 7월 31일
댓글: K E 2014년 8월 4일
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.
  댓글 수: 2
K E
K E 2014년 8월 4일
This works, thanks! (and working = virtuous for this application).
Star Strider
Star Strider 2014년 8월 4일
My pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (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