Warm tip: This article is reproduced from serverfault.com, please click

How to get better Plots.jl xaxis tick labels with Time data in Julia?

发布于 2020-12-08 19:57:08

I would like to see [00:00:00, 02:00:00, 04:00:00, 06:00:00] or similar as the xtick labels. The pyplot and GR backends gave similar results. I am fine using any backend that supports both a left and right yaxis.

Default Plot

using DataFrames, Dates, Plots
gr(linewidth=3, markersize=4, titlefont=18, legendfont=12, guidefont=18, tickfont=14, legend=:outertopright)
df = DataFrame()
df.Time = ["0:05:02", "1:05:23", "2:05:34", "4:05:42", "5:36:01"]
df.Data = [0.0, 1.0, 0.5, 0.4, 0.1]
df.Time = Time.(df.Time, DateFormat("H:M:S"))
plot(df.Time, df.Data)

default.png

My Attempts

julia> plot(df.Time, df.Data, lims = :round)

lims.png

julia> plot(df.Time, df.Data, ticks = 4)

ticks.png

julia> plot(df.Time, df.Data, lims = :round, ticks = 4)

lims_ticks.png

julia> plot(df.Time, df.Data, xlims = (Time(0), Time(6)))
ERROR: MethodError: no method matching Float64(::Time)
Closest candidates are:
  Float64(::UInt32) at float.jl:66
  Float64(::Int128) at float.jl:94
  Float64(::Float16) at float.jl:256
  ...
Stacktrace:
 [1] (::RecipesPipeline.var"#7#8"{Symbol})(::Time) at C:\Users\nboyer.AIP\.julia\packages\RecipesPipeline\uPBKQ\src\utils.jl:201
 [2] optimal_ticks_and_labels(::Plots.Subplot{Plots.GRBackend}, ::Plots.Axis, ::Nothing) at C:\Users\nboyer.AIP\.julia\packages\Plots\vsE7b\src\axes.jl:167
julia> plot(df.Time, df.Data, xticks = Time(0):Hour(2):Time(6))

xticks.png

The last attempt setting xticks is close, but I still can't get the last tick to appear. Interestingly, it doesn't matter what I set the last value of the range to be. xticks = Time(0):Hour(2):Time(10) produces the same image.

Questioner
Nathan Boyer
Viewed
2
MarcMush 2020-12-10 19:27:18

This will work :

plot(df.Time, df.Data, 
     xlims = (Dates.value(Time(0)), Dates.value(Time(6))), 
     xticks = Time(0):Hour(2):Time(6)
)

I feel this should be possible without Dates.value.

Very recently, support was added for Date and DateTime (https://github.com/JuliaPlots/Plots.jl/pull/3180), but not Time or TimePeriod