# Shade an area in a plot between two Y values

463 views (last 30 days)
Christoph Meier on 15 Sep 2015
Dear MATLAB community,
I have a time series plot, and would like to shade specific regions in light grey (transparent).
The time series plot is an economic process, and I would like to shade times of recessions.
That is, I already have the values of the y-axis (the respective start date and end date of a recession), and I already have a nice plot, but I cannot figure out how to add these 'recession shadings'.
In short: I would like to shade an area in a time series plot, and the area is defined as:
X(:) % all x
Y(y1,y2) % between y1 and y2
Thank you!

Star Strider on 16 Sep 2015
Edited: Star Strider on 16 Sep 2015
See if this does what you want:
x = linspace(0, 10, 10);
y = randi(9, 1, 10);
ybars = [2 6];
figure(1)
hp = plot(x, y, 'bp');
hold on
patch([min(xlim) max(xlim) max(xlim) min(xlim)], [ybars(1) ybars(1), ybars(2) ybars(2)], [0.8 0.8 0.8])
plot(x, y, 'bp')
hold off
axis([0 10 0 10])
You will have to modifiy it to do what you want, but that should be straightforward. Note the repeated plot call to prevent the patch from hiding it.

Star Strider on 16 Sep 2015
And as always, my pleasure!
jen Magnes on 11 Jul 2018
Star Strider on 11 Jul 2018
As always, my pleasure!

Thanks a lot ,Star Strider!

Star Strider on 14 Aug 2017
My pleasure!
Jonathan Bishop on 24 May 2019
Didn't spend more than a minute on this so possibly there is more to it, but if using a legend, both the patch and the double call to plot will affect the current spot in the ordered list of plot colors. Set the patch handlevisibility to 'off' and use cla after the first plot, if you don't want to bother dealing with the color order in a more programmatic fashion.

A K M Kamrul Hasan on 22 Jan 2020
Hi,
This discussion is about the srea bounded by straight lines. However, is it possible to shade an area in Matlab plot bounded by straight lines and curved lines? (i.e like the attached image) ?
Regards,
Kamrul Hasan

Star Strider on 22 Jan 2020
Yes.
A K M Kamrul Hasan on 22 Jan 2020
May I know the necessary commands for that?