필터 지우기
필터 지우기

How can I add recession bars to a time series plot?

조회 수: 13 (최근 30일)
Sabarna Mukherjee
Sabarna Mukherjee 2023년 9월 21일
댓글: Sabarna Mukherjee 2023년 9월 23일
Actually, I want to plot variable x against quarters from 2001Q1 to 2023Q1 and then add shaded recession bars to the plot. In the attached file I also have the U.S. nber recession indicator which is a dummy variable. 1 meaning recession and 0 meaning no recession.
The MATLAB codes I have written are as:
function rescode1;
data = readtable('example_data.xlsx');
qdates = data(:,4);
usrecq = data(:, 2);
x = data(:,3);
figure;
for i= 1:length(usrecq);
if usrecq==1;
recessionplot;
end;
end;
hold on;
plot(qdates,x, '-', 'LineWidth',2);
title('Time series plot of x');
xlabel('Quarters');
ylabel('Y axis');
ax = gca;
ax.XAxis.TickLabels = ({'2001q1','2002q1','2003q1','2004q1','2005q1','2006q1','2007q1','2008q1','2009q1','2010q1','2011q1', '2012q1','2013q1','2014q1','2015q1','2016q1','2017q1','2018q1','2019q1','2020q1','2021q1','2022q1','2023q1'});
xticks([1 5 9 13 17 21 25 29 33 37 41 45 49 53 57 61 65 69 73 77 81 85 89])
Using the above code I cannot generate the recession bars.
Need some suggestions.
Thank you.

채택된 답변

Chunru
Chunru 2023년 9월 21일
편집: Chunru 2023년 9월 22일
data = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/1488862/example_data.xlsx');
y = data.var3; x=data.quarters; r = data.usrecq;
plot(x, y, '-', 'LineWidth',2)
hold on;
yl = ylim;
xr = x(r>0.5);
yr = yl(2)*ones(size(xr));
width = 1;
bar(xr, yr, width, 'FaceColor', [0.8 0.8 0.8], 'EdgeColor', 'none', ...
'BaseValue', yl(1), 'FaceAlpha', 0.3);
%bar(x(r>0.5), y(r>0.5))
ylim(yl)
title('Time series plot of x');
xlabel('Quarters');
ylabel('Y axis');
ax = gca;
ax.XAxis.TickLabels = ({'2001q1','2002q1','2003q1','2004q1','2005q1','2006q1','2007q1','2008q1','2009q1','2010q1','2011q1', '2012q1','2013q1','2014q1','2015q1','2016q1','2017q1','2018q1','2019q1','2020q1','2021q1','2022q1','2023q1'});
xticks([1 5 9 13 17 21 25 29 33 37 41 45 49 53 57 61 65 69 73 77 81 85 89])
  댓글 수: 3
Chunru
Chunru 2023년 9월 22일
See the modification above.
Sabarna Mukherjee
Sabarna Mukherjee 2023년 9월 23일
Thank you so much for your help and suggestions. The code worked!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Time Series Events에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by