Graph Tips – IX: Recession Shadings

Next a graph which includes shadings for recessions. Some plotly trickery is required to get recession shading bars (which are actually quite difficult to do, at least the first time). This example will actually mostly be useful for cut-and-paste to implement recession shading bars in your own graphs.

Matlab code for plot of US GDP with NBER Recession Shadings :
% First: Import the GDP and NBER Recession dating data
% Gross Domestic Product by Expenditure in Constant Prices: Total Gross Domestic Product for the United States (quarterly, seasonally adjusted)
fred_GDP = getFredData(‘NAEXKP01USQ652S’, ‘1970-01-01’, ‘2015-06-30’)
% NBER based Recession Indicators for the United States from the Period following the Peak through the Trough (+1 or 0, Quarterly, Not Seasonally Adjusted)
fred_USRECQ = getFredData(‘USRECQ’, ‘1970-01-01’, ‘2015-06-30’)
% Create the regression shading. I do this separately to the rest of the graph just to as to make it easier to add to your own graphs
traceUSRECQ= struct(‘x’, {cellstr(datestr(fred_USRECQ.Data(:,1),’yyyy-QQ’))},’y’,fred_USRECQ.Data(:,2),’name’,'(Recession)’,’type’, ‘scatter’,’fill’,’tozeroy’,’showlegend’,false,’line’, struct(‘color’,’rgb(200,200,200)’,’width’,0,’opacity’,0.2,’shape’,’hvh’),’yaxis’, ‘y2′,’marker’, struct(‘size’, 0));
axisUSRECQ=struct(‘title’, ‘ ‘,’showticklabel’,false,’autotick’,false,’tickfont’,struct(‘color’, ‘white’),’linewidth’,0,’showgrid’,false,’zeroline’,false,’side’, ‘left’);
% Graph of US RGDP
trace1= struct(‘x’, {cellstr(datestr(fred_GDP.Data(:,1),’yyyy-QQ’))},’y’,fred_GDP.Data(:,2),’name’,’US GDP’,’type’, ‘scatter’);
data = {trace1,traceUSRECQ};
layout = struct(‘title’ ‘US Real GDP’,’showlegend’, true,’width’, 800,…
‘xaxis’, struct(‘domain’, [0, 1],’title’,’Year’,’showgrid’,false), …
‘yaxis’, struct(‘title’, ‘GDP’,’titlefont’, struct(‘color’, ‘black’),’tickfont’, struct(‘color’, ‘black’),’side’, ‘left’,’position’,0,’overlaying’, ‘y2’),…
‘yaxis2’, axisUSRECQ,…
‘legend’, struct(‘x’,0,’y’,1));
response = plotly(data, struct(‘layout’, layout, ‘filename’,’US_RGDP’, ‘fileopt’, ‘overwrite’));
% Graph has been created with name US_RGDP, but let’s save a pdf copy to inside a folder called Graphs (folder must already exist or matlab will error); response.layout=layout;
saveplotlyfig(response, ‘./Graphs/US_RGDP.pdf’)
% Note: Graph in link does not include the graph title, and uses a different time period, and forces the line color to be blue, but otherwise the same.

Leave a Reply

Your email address will not be published. Required fields are marked *