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

9 Ansichten (letzte 30 Tage)
Sabarna Mukherjee
Sabarna Mukherjee am 21 Sep. 2023
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.

Akzeptierte Antwort

Chunru
Chunru am 21 Sep. 2023
Bearbeitet: Chunru am 22 Sep. 2023
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 Kommentare
Chunru
Chunru am 22 Sep. 2023
See the modification above.
Sabarna Mukherjee
Sabarna Mukherjee am 23 Sep. 2023
Thank you so much for your help and suggestions. The code worked!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Conditional Mean Models finden Sie in Help Center und File Exchange

Produkte


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by