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

6 次查看(过去 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.

采纳的回答

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 个评论
Sabarna Mukherjee
Sabarna Mukherjee 2023-9-23
Thank you so much for your help and suggestions. The code worked!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Conditional Mean Models 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by