5
$\begingroup$

I have a time series plot

DateListPlot[{1, 1, 2, 3, 5, 8, 11, 13, 17, 21}, {2000, 8, 6}]

I would like to have a background which is white upto Aug 10 and yellow from Aug 10 on to enphasize these later days. In general: how can you have different background colors on different dates?

I think I saw this done in the documentation center, but cannot find where.

Can you suggest how to do it?

$\endgroup$

2 Answers 2

4
$\begingroup$

The x-axis of the plot is given in AbsoluteTime. You can convert your start and end dates using AbsoluteTime and then plot the background using Prolog. Example:

DateListPlot[
 {1, 1, 2, 3, 5, 8, 11, 13, 17, 21},
 {2000, 8, 6},
 Prolog -> {
   Yellow,
   Rectangle[
    {AbsoluteTime[{2000, 8, 11}], -100},
    {AbsoluteTime[{2000, 8, 13}], 100}]
   }]

Plot with background

$\endgroup$
1
  • $\begingroup$ Prolog, of course! this is exactly what I was looking for. Down in the Prolog documentation page there is the background example I thought of remembering. $\endgroup$
    – magma
    Commented Apr 8, 2020 at 0:02
6
$\begingroup$
SeedRandom[7777]
vals = RandomInteger[100, 50];

dts = DateRange[{2000, 8, 6}, DatePlus[{2000, 8, 6}, {Length @ vals, "Day"}], "Day"];

dateintervals = dts[[#]] & /@ Partition[Sort[RandomSample[Range[Length@vals], 6]], 2];

dlp = DateListPlot[vals, {2000, 8, 6}];

dlp2 = DateListPlot[Thread[{#, PlotRange[dlp][[2, 1]]}] & /@ dateintervals, 
   Filling -> Top, 
   FillingStyle -> Opacity[.5], 
   PlotStyle -> "LineOpacity" -> 0, 
   PlotRange -> PlotRange[dlp], 
   PlotLegends -> SwatchLegend[Automatic, 
     Row[#, " - "] & /@ Map[DateObject[#, "Day"] &, dateintervals, {-2}], 
     BaseStyle -> Opacity[.5], LegendMarkerSize -> 20]];

Show[dlp, dlp2, dlp, ImageSize -> Large]

enter image description here

Use

PlotStyle -> (Directive["LineOpacity" -> 0, #] & /@ {Orange, Red, Green})

to get

enter image description here

$\endgroup$
1
  • $\begingroup$ Thank you kglr, very interesting answer, but @C.E.'s is closer to what I had in mind $\endgroup$
    – magma
    Commented Apr 8, 2020 at 0:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.