Rollo99
Rollo99

Reputation: 1613

How to shade rectangles in MATLAB with time on the x axis?

I am trying to plot gray rectangulars on this plot:

t1 = datetime(2002,02,01);
t2 = datetime(2019,11,01);
t = t1:calmonths:t2;
t= datenum(char(t),'dd-mm-yyyy')

plot(t, randn(214,1), 'LineWidth',1,'Color', [0 0 0]);
ax.XTick = t(1:end);
datetick('x','yyyy','keepticks');
yline(0,'-')
ylabel('%')

I would like to have two shaded areas: one that goes from April 2009 to October 2010 and another one that goes from January 2003 to October 2015. I did this in the past but with time on the x-axis complicates it, at least for me.

Can anyone help me out?

Upvotes: 1

Views: 117

Answers (1)

Marouen
Marouen

Reputation: 945

Here is an attempt

t1 = datetime(2002,02,01);
t2 = datetime(2019,11,01);
t = t1:calmonths:t2;
t= datenum(char(t),'dd-mm-yyyy');

figure;
hold on

% 1st shaded area
d1=datenum(datetime(2003,01,01));
d2=datenum(datetime(2015,10,01));
x=[[d1,d2],[d2,d1],d1];
y=[-[3,3],[3,3],[-3]];
fill(x, y, 'r');

% 2nd shaded area
d1=datenum(datetime(2009,04,01));
d2=datenum(datetime(2010,10,01));
x=[[d1,d2],[d2,d1],d1];
y=[-[3,3],[3,3],[-3]];
fill(x, y, 'g');

% Time-series
plot(t, randn(214,1), 'LineWidth',1,'Color', [0 0 0]);
ax.XTick = t(1:end);
datetick('x','yyyy','keepticks');
yline(0,'-')
ylabel('%')

You can play on the transparency (alpha) to make it even prettier.

Upvotes: 1

Related Questions