在matlab中使用阴影条区域叠加线图

时间:2014-11-11 09:32:19

标签: matlab plot fill

我希望在Matlab中使用彩色条形图覆盖我的线条图,以获得不同的x轴值。我正在寻找的功能与recessionplot()非常相似,但它不应表示NBER衰退,而是表示用户定义的时段。我可以使用以下代码执行此操作,但原始行的颜色已更改。如何以最佳方式避免这种情况?

%%%%%%%%%%%% 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

1 个答案:

答案 0 :(得分:3)

保存绘制对象的句柄:

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

然后使用此功能(在<{1}}之后的之后):

shadedates

(我来自here