Plots with formatted DateTime xticks?

I need to plot some data with DateTime type along the abscissa, and would like to have a nice formatting of the xtick argument.

Consider this example:

using Plots, Dates
function timeperiod(x::Float64)
    Second(Int(floor(Second(Day(1)).value * x)))
today = DateTime(2010,10,19)
x = range(0,60,length=100)
tm = today+timeperiod.(x);

which gives:

I’d like to indicate the time every week, so I try with:

tm_tick = range(tm[1],tm[end],step=Day(7))

leading to:

As seen, this provides unnecessary time resolution (ms?) and the year “disappears”.

So I try with:

julia> Dates.format.(tm_tick,"yyyy-mm-dd")
5-element Array{String,1}:

which would be an ok formatting. HOWEVER, if I try with:


the plot is produced without xticks…

Question: How can I achieve the desired formatting of the xticks?

[I need to abscissa values `tm` to be of type `DateTime` and not `Date`, because I have much higher resolution than once a day. For my use, the `x` vector will not have equidistant elements.]

The xticks option receives both the positions and labels of the ticks, so you can do:

julia> ticks = Dates.format.(tm_tick,"yyyy-mm-dd");

julia> plot(tm,sin.(2pi*x/28),xticks=(tm_tick,ticks),xrot=60)



Great! Thanks!
[Eh… I missed today by 10 years… :blush: ]

1 Like