I have a time series plot, and would like to shade specific regions in light grey (transparent) like this
I cannot figure out how to add these 'recession shadings' in a ListLinePlot
.
Thank you!
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityYou can include them as Rectangle
objects in the Prolog
of the plot:
ts = RandomReal[{-.6, 1.2}, 100];
ListLinePlot[
ts,
Prolog -> {GrayLevel[0.85],
Rectangle[{1000, -100}, {2500, 100}],
Rectangle[{5000, -100}, {5700, 100}]
},
PlotStyle -> Red,
Frame -> True, Axes -> False,
FrameTicks -> {{Automatic, None}, {Automatic, None}}
]
Using Prolog
ensures that the plot is drawn on top of them, so they do not need to be transparent. Alternatively, if you do want transparency, you can control that by adding an Opacity
directive after the color selection in the Prolog
.
The top and bottom edges of the rectangles have been arbitrarily set to -100 and +100 in the code above; if that is not enough to make sure that the edges are well outside of the plot's range, they can be adjusted manually.
data = RandomReal[{-6, 12}, 10];
{n, x} = Through[{Min, Max}[data]];
ListLinePlot[data,
Prolog -> {LightGray, Rectangle[##] & @@@
{{{2, n}, {4, x}},
{{5, n}, {8, x}}}},
Frame -> True, PlotStyle -> Orange]
Or
ListLinePlot[{data,
{{2, n}, {4, n}}, {{2, x}, {4, x}},
{{5, n}, {8, n}}, {{5, x}, {8, x}}},
Frame -> True, PlotStyle -> {Orange, None, None, None, None},
Filling -> {{2 -> {{3}, LightGray}}, {4 -> {{5}, LightGray}}}]
SeedRandom[77777]
values = Accumulate /@ RandomVariate[NormalDistribution[], {5, 300}];
dates = Range@300;
data = Thread[{dates, #}] & /@ values;
recessions = {{20, 35}, {95, 120}, {180, 240}};
Combine two ListLinePlot
s, one for the original time series and the second for recessions
, using Show
:
llp = ListLinePlot[ data];
llp2 = ListLinePlot[Thread[{#, PlotRange[llp][[2, 1]]}] & /@ recessions,
Filling -> Top, FillingStyle -> Opacity[.25, Gray], PlotStyle -> None,
PlotRange -> PlotRange[llp]];
Show[llp, llp2, Frame -> True]
dates = DateRange[{1990, 1}, DatePlus[{1990, 1}, {299, "Month"}], "Month"];
data = Thread[{dates, #}] & /@ values;
recessions = {{{1995, 1}, {1998, 2}}, {{2001, 2}, {2003, 1}}, {{2009, 5}, {2011, 2}}};
Combine two DateListPlot
s, one for the original time series and the second for recessions
, using Show
:
dlp = DateListPlot[data, Joined -> True];
dlp2 = DateListPlot[Thread[{#, PlotRange[dlp][[2, 1]]}] & /@ recessions,
Joined -> True, Filling -> Top, FillingStyle -> Opacity[.25, Gray],
PlotStyle -> None, PlotRange -> PlotRange[dlp]];
Show[dlp, dlp2]