Search code examples
matlabplotfill

Overlay line plot with shaded bar areas in matlab


I want to overlay my line plot in Matlab with colored bars for different x-axis values. The functionality I'm looking for is much like recessionplot(), but it should not indicate NBER recessions, but user defined periods. I'm able to do this with the following code, but the color of my original line is changed. How do I avoid this in the best way?

%%%%%%%%%%%% Functions to shade %%%%%%%%%%%%%%%%%%%

function []=shadedates(Start,Finish,colorstr)
curax=axis;
indx1=find(Finish>curax(1));  % First Date to include;
indx2=find(Start<curax(2));  % Last Date to include;
indx1=indx1(1);
indx2=indx2(length(indx2));
if Start(indx1)<curax(1);
  Start(indx1)=curax(1);
end;
if Finish(indx2)>curax(2);
  Finish(indx2)=curax(2);
end;

shade(Start(indx1:indx2),Finish(indx1:indx2),colorstr);

end

function []=shade(Start,Finish,colorstr)
%  Start and Finish are Nx1 vectors of starting and ending years.
%  The function shades between the start and finish pairs using colorstr


if ~exist('colorstr','var'); colorstr='y'; end;  % default is yellow
curax=axis;
y=[curax(3) curax(4) curax(4) curax(3)];
hold on;
for i=1:length(Start);
  x=[Start(i) Start(i) Finish(i) Finish(i)];
  h=fill(x,y,colorstr);
  set(h,'facealpha',.3)
end;

h = findobj(gca,'Type','patch');
set(h,'EdgeColor','none');

% This last one makes the tick marks visible
set(gca, 'Layer', 'top')
end

%%%%%%%%%%%%%%% Create data %%%%%%%%%%%%%%%%%%%%%%
GLI.Dates = transpose(714890:(714890+99));
GLI.GLI = cumsum([50;normrnd(0,1,99,1)]);

GLI.ProsStart = zeros(size(GLI.GLI));
GLI.RecStart = zeros(size(GLI.GLI));
GLI.ProsFin = zeros(size(GLI.GLI));
GLI.RecFin = zeros(size(GLI.GLI));
TempLag = GLI.GLI(1);
CurPhase = 0;

for i=2:size(GLI.GLI,1)
    Temp = GLI.GLI(i);
    if Temp > TempLag && CurPhase ~= 1
        GLI.ProsStart(i-1) = 1;
        if CurPhase == 2
            GLI.RecFin(i-1) = 1;
        end
        CurPhase = 1;
    elseif Temp < TempLag && CurPhase ~= 2
        GLI.RecStart(i-1) = 1;
        if CurPhase == 1
            GLI.ProsFin(i-1) = 1;
        end
        CurPhase = 2;
    end
    TempLag = Temp;
end
if CurPhase == 1
    GLI.ProsFin(end) = 1;
elseif CurPhase == 2
    GLI.RecFin(end) = 1;
end

%%%%%%%%%%%%%%%%%%% Create plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
plot(GLI.Dates,GLI.GLI)
colorstr=[0 1 0];
shadedates(GLI.Dates(logical(GLI.ProsStart)),GLI.Dates(logical(GLI.ProsFin)),colorstr)
colorstr=[1 0 0];
shadedates(GLI.Dates(logical(GLI.RecStart)),GLI.Dates(logical(GLI.RecFin)),colorstr)

Resulting plot


Solution

  • save a handle to the plotted object:

    p = plot(GLI.Dates,GLI.GLI)
    

    and then use this (after the calls to shadedates):

    uistack(p,'top')
    

    (I have this from here)