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)))
end
#
today = DateTime(2010,10,19)
x = range(0,60,length=100)
tm = today+timeperiod.(x);
#
plot(tm,sin.(2pi*x/30))

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))
#
plot(tm,sin.(2pi*x/28),xtick=tm_tick,xrot=60)

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}:
 "2010-10-19"
 "2010-11-02"
 "2010-11-16"
 "2010-11-30"
 "2010-12-14"

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

plot(tm,sin.(2pi*x/28),xtick=Dates.format.(tm_tick,"yyyy-mm-dd"),xrot=60)

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.]

2 Likes

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)

test

7 Likes

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

1 Like

What if I want to use the default positions? In other words, just change the date format?