diff --git a/axis.go b/axis.go index 4eacdd78..f01927d2 100644 --- a/axis.go +++ b/axis.go @@ -462,9 +462,18 @@ func (ts ConstantTicks) Ticks(float64, float64) []Tick { return ts } -// UnixTimeTicks is suitable for axes representing time values. -// UnixTimeTicks expects values in Unix time seconds. -type UnixTimeTicks struct { +// UnixTimeIn returns a time conversion function for the given location. +func UnixTimeIn(loc *time.Location) func(t float64) time.Time { + return func(t float64) time.Time { + return time.Unix(int64(t), 0).In(loc) + } +} + +// UTCUnixTime is the default time conversion for TimeTicks. +var UTCUnixTime = UnixTimeIn(time.UTC) + +// TimeTicks is suitable for axes representing time values. +type TimeTicks struct { // Ticker is used to generate a set of ticks. // If nil, DefaultTicks will be used. Ticker Ticker @@ -472,27 +481,33 @@ type UnixTimeTicks struct { // Format is the textual representation of the time value. // If empty, time.RFC3339 will be used Format string + + // Time takes a float64 value and converts it into a time.Time. + // If nil, UTCUnixTime is used. + Time func(t float64) time.Time } -var _ Ticker = UnixTimeTicks{} +var _ Ticker = TimeTicks{} // Ticks implements plot.Ticker. -func (utt UnixTimeTicks) Ticks(min, max float64) []Tick { - if utt.Ticker == nil { - utt.Ticker = DefaultTicks{} +func (t TimeTicks) Ticks(min, max float64) []Tick { + if t.Ticker == nil { + t.Ticker = DefaultTicks{} + } + if t.Format == "" { + t.Format = time.RFC3339 } - if utt.Format == "" { - utt.Format = time.RFC3339 + if t.Time == nil { + t.Time = UTCUnixTime } - ticks := utt.Ticker.Ticks(min, max) + ticks := t.Ticker.Ticks(min, max) for i := range ticks { tick := &ticks[i] if tick.Label == "" { continue } - t := time.Unix(int64(tick.Value), 0) - tick.Label = t.Format(utt.Format) + tick.Label = t.Time(tick.Value).Format(t.Format) } return ticks } diff --git a/plotter/testdata/timeseries_golden.png b/plotter/testdata/timeseries_golden.png index 02a8d91b..c4d358f1 100644 Binary files a/plotter/testdata/timeseries_golden.png and b/plotter/testdata/timeseries_golden.png differ diff --git a/plotter/timeseries_test.go b/plotter/timeseries_test.go index 568b1584..696b15c5 100644 --- a/plotter/timeseries_test.go +++ b/plotter/timeseries_test.go @@ -20,6 +20,9 @@ import ( func Example_timeSeries() { rnd := rand.New(rand.NewSource(1)) + // xticks defines how we convert and display time.Time values. + xticks := plot.TimeTicks{Format: "2006-01-02\n15:04"} + // randomPoints returns some random x, y points // with some interesting kind of trend. randomPoints := func(n int) XYs { @@ -48,7 +51,7 @@ func Example_timeSeries() { log.Panic(err) } p.Title.Text = "Time Series" - p.X.Tick.Marker = plot.UnixTimeTicks{Format: "2006-01-02"} + p.X.Tick.Marker = xticks p.Y.Label.Text = "Number of Gophers\n(Billions)" p.Add(NewGrid())