7
$\begingroup$

I have this data and I want to plot it with six dates on the x-axis. The first tick should be the first data points date minus two days and the last tick should be the last data points date plus two days. New information may be entered so I cannot explicitly set the tick marks I want. They must be recalculated every time a new plot is generated.

Thank you

data = {{DateObject[{2021, 1, 21}], 201.8},
   {DateObject[{2021, 1, 22}], 203.6}, 
   {DateObject[{2021, 1, 25}], 202.5},
   {DateObject[{2021, 1, 26}], 201.4},
   {DateObject[{2021, 1, 27}], 201.1},
   {DateObject[{2021, 1, 29}], 201.6},
   {DateObject[{2021, 1, 30}], 201.1},
   {DateObject[{2021, 1, 31}], 200.7},
   {DateObject[{2021, 2, 1}], 200.1}};
DateListPlot[data, Joined -> False, LabelStyle -> {12, GrayLevel[0]}, DateTicksFormat -> {"MonthShort", "/", "Day"}]
$\endgroup$

3 Answers 3

7
$\begingroup$

You can control the ticks explicitly with FrameTicks, but don't forget to adjust the PlotRange. Date algebra can be performed with DatePlus.

minmax = MinMax[data[[All, 1]]];
min = DatePlus[minmax[[1]], -2];
max = DatePlus[minmax[[2]], 2];

DateListPlot[data, Joined -> False, LabelStyle -> {12, GrayLevel[0]}, 
 PlotRange -> {{min, max}, Automatic},
 FrameTicks -> {{Automatic, None}, {DateRange[min, max], None}},
 DateTicksFormat -> {"MonthShort", "/", "Day"}]

DateListPlot

$\endgroup$
5
$\begingroup$
data = {{DateObject[{2021, 1, 21}], 
    201.8}, {DateObject[{2021, 1, 22}], 
    203.6}, {DateObject[{2021, 1, 25}], 
    202.5}, {DateObject[{2021, 1, 26}], 
    201.4}, {DateObject[{2021, 1, 27}], 
    201.1}, {DateObject[{2021, 1, 29}], 
    201.6}, {DateObject[{2021, 1, 30}], 
    201.1}, {DateObject[{2021, 1, 31}], 
    200.7}, {DateObject[{2021, 2, 1}], 200.1}};

incr = (QuantityMagnitude[
      DateDifference[data[[1, 1]], data[[-1, 1]]]] + 4)/5;

ticks = DateRange[DatePlus[data[[1, 1]], -2], 
   DatePlus[data[[-1, 1]], 2], incr];

DateListPlot[data,
 PlotRange -> {{ticks[[1]], ticks[[-1]]}, Automatic},
 Joined -> False,
 LabelStyle -> {12, GrayLevel[0]},
 FrameTicks -> {{Automatic, Automatic},
   {ticks, None}},
 DateTicksFormat -> {"MonthShort", "/", "Day"}]

enter image description here

$\endgroup$
4
$\begingroup$
Clear[ticks, prange, n]
prange = DateBounds[data[[All, 1]]] + Quantity[#, "Days"] &@{-2, 2}
ticks[n_] := DateRange[Splice@prange, n]

DateListPlot[data
 , Joined -> False, LabelStyle -> {12, GrayLevel[0]}
 , DateTicksFormat -> {"MonthShort", "/", "Day"}
 , PlotRange -> {prange, Automatic}
 , FrameTicks -> {{Automatic, None}, {ticks[3], None}}
 , GridLines -> {ticks[1], Automatic}
 ]

enter image description here

$\endgroup$

Your Answer

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

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