4
$\begingroup$

I want to do a datelistplot with a temporal data, and then i want to highlight in the plot an interval of data between two dates. the highlight i want to do is put a rectangle behind the plot.

I tried to run an example but didnt work

data = FinancialData["AAPL", "Jan. 1, 2021"];
plot = DateListPlot[data, PlotStyle -> Blue];

highlight = {{DateObject[{2021, 3, 1}], DateObject[{2021, 6, 1}], 
    Directive[Red, Opacity[0.2]]}, {DateObject[{2021, 9, 1}], 
    DateObject[{2021, 12, 1}], Directive[Green, Opacity[0.2]]}};

Show[plot, Epilog -> Rectangle @@@ highlight]

kind regards

$\endgroup$

2 Answers 2

8
$\begingroup$

One solution:

    plot = DateListPlot[
             {data,
              TimeSeriesWindow[data, {DateObject[{2021, 3, 1}], DateObject[{2021, 6, 1}]}], 
              TimeSeriesWindow[data, {DateObject[{2021, 9, 1}], DateObject[{2021, 12, 1}]}]}, 
              PlotStyle -> Blue,
              Filling -> {
                 None, 
                 2 -> {Axis, Directive[Red, Opacity[0.2]]}, 
                 3 -> {Axis, Directive[Green, Opacity[0.2]]}}]

enter image description here

$\endgroup$
1
  • $\begingroup$ Thanks, it is a interesting way to do it! $\endgroup$
    – Renato QE
    Dec 15, 2023 at 2:15
7
$\begingroup$

1.

Show[plot, 
 Epilog -> ({#3, Rectangle[{#, 0}, {#2, First @ Max @ data}]} & @@@
   (highlight /. d_DateObject :> AbsoluteTime[d]))]

enter image description here

2.

DateListPlot[{data, ## & @@ (Thread[{{#, #2}, Max@data}] & @@@ highlight)}, 
 PlotStyle -> {Blue, None, None}, 
 Filling -> MapThread[{# -> {Axis, #2}} &]@{{2, 3}, highlight[[All, -1]]}]

enter image description here

$\endgroup$
1
  • $\begingroup$ Thanks the first one seems simple for me. kind regards $\endgroup$
    – Renato QE
    Dec 15, 2023 at 2:56

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.