How can I shade the background of a timeseries plot based on another value.

I have the following code:
days = [152:272]; %n = 120
PA = [0 0 0 0 1 1 1 1....1 0]; % 1 or 0 for each of the 120 day time series
I would like to shade the back of the plot blue when PA = 1 and yellow when PA = 0
I am going to plot another line in front of the color patches.

 Accepted Answer

You could do something like this,
%some data
days = 100:199;
PA = repmat([0 0 0 0 1 1 1 1 1 1],1,10);
%PA = 1 -> blue background
[x,y] = stairs(days,PA);
area(x,y,'edgecolor','none','facecolor','b')
%otherwise yellow background
set(gca,'color','y')

6 Comments

Thanks, this is close but the blue banding only goes up to 1 on the y axis. (the third variable that I am plotting as a line over the colored background has a much bigger range so essentially the whole plot appears yellow). Also, when I do the following:
hold on
plot(days,BFET_233)
all of the formatting is reset. How can I plot a solid black line over the background
Just multiply PA by something large. Not sure why format is reset, should not happen. Could you post the relevant part of your code?
blue = 1/255*[186,210,223];
yellow = 1/255*[248,223,149];
%PA = 1 -> blue background
[x,y] = stairs(days,PA_233*2000);
area(x,y,'edgecolor','none','facecolor',blue)
%otherwise yellow background
set(gca,'color',yellow)
hold on
plot(days,BFET_233,'k')
ylim([-1 10])
I would like the blue portion to extend from 2000 to -2 on the y axis, not sure how to make it both positive and negative
This should do it. You just need to experiment with the basevalue-property of the stairs-objects and the y-values derived from PA.
%some data
days = 100:199;
PA = repmat([0 0 0 0 1 1 1 1 1 1],1,10);
%get cornerpoints for blue areas
[x,y] = stairs(days,PA);
%let blue background go from -2000 to 2000
y = y.*4e3 - 2e3;
a = area(x,y,'edgecolor','none','facecolor','b')
%adjust basevalue
a.BaseValue = min(y);
%set axes background to yellow
set(gca,'color','y')
hold on
%plot some data
plot([100,200],[-2,2000],'k')
%change axis to your desired limits
axis([min(days),max(days),-2,2000])

Sign in to comment.

More Answers (0)

Asked:

on 17 Jul 2020

Commented:

on 17 Jul 2020

Community Treasure Hunt

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

Start Hunting!