Shading to indicate a condition on a time series plot
조회 수: 14 (최근 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
댓글 수: 0
채택된 답변
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개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Annotations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!