How can I add recession bars to a time series plot?
조회 수: 17 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
채택된 답변
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])
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Time Series Events에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!