How to change date format and keep the type of variable?


#1

Hi.

I have an array of dates that I want to use on a xaxis of a plot. These dates I need to present as an abbreviated month/ abbreviated year way (For example: “Jan-18”, “Feb-18”, and so on). The problem shows up when I use Dates.format function. This converts my array of type Date to type string. So, what happens in my x axis plot is an alphabetically ordering, what is incorrect.

I think that if I could keep my array type, my x axis would order the dates in a correct way. How could I convert data format but keep the type? Is there a way to do that?

Thanks.


#2

this may not be the most general solution, but you can have your x-tick labels be a tuple of vectors.

xticks = ([1,2,3], String.([1,2,3]))

#3

I’m sorry, I didn’t understand… Actually, this piece of code didn’t work here. How could I make a parallel with my case?


#4

We need an MWE to give you exact code, but here is some code I made the other day that works

 xticks = ([30, 50, 105], ["2-year endline", "4-year endline", "9-year endline"])

I would imagine that you have a vector of dates for dates, so you could write

xticks = (mydates, Dates.format.(mydates))

#5

Here is a generic way of doing this in Gadfly:

using Base.Dates, DataFrames, Gadfly
dates = Date("2000-01-15"):Month(1):Date("2017-12-15")
dict1 = Dict(Dates.value(x) => Dates.format(x, "u-yy") for x in dates)

t = Dates.value.(dates)
D = DataFrame(t=t, date=dates, y= -cos.(2π*t/365.25))

pa = plot(D, x=:t, y=:y, Geom.line,
        Guide.xticks(ticks=t[1:6:end]), # location of tickmarks
        Scale.x_continuous(labels=i->dict1[i])
    )
draw(PNG(8inch,3inch), pa)


Note that if you omit ticks and labels, then Gadfly will try to pick suitable values, e.g.

pb = plot(D[1:24,:], x=:date, y=:y, Geom.line,
    Guide.xticks(orientation=:vertical)
)
draw(PNG(8inch,3inch),pb)


#6

@genauguy Thank you, I’m sure that your explanation will be very useful for me.

@Mattriks Thank you very much, your example was very helpful. It seems that you used a specific argument of the Gadfly pkg to change the xaxis label, but for my application, I really need an array of dates with a personalized format but still of type date, if it were possible, sure. Something like Excel, where we change a number format to a month/year, for example, but although we see a “string”, we still have a number. I’m sure that if it was possible, I could correctly order my x-axis plot.

Another option, if it were possible, could be change the levels of my array of dates (as strings) and impose a “monthly” ordering. Is that possible one of these two options in Julia?


#7

I think the issue here is that a julia Date object doesn’t store a string representation of itself e.g. dump(Date("2018-01-01")), the string representation only exists when you format/print it in some way (some might say it’s quantum!). See the docs for more info: https://docs.julialang.org/en/stable/manual/dates/.